0
對於作業我嘗試發送一個文件和一些參數對應這個文件。 所以,我發送我的文件和我的字符串後。 問題是我的參數轉到我的文件,而不是我的變量。我理解這個問題,我的循環在繼續寫入文件時只要他收到了一些東西,但是我想停止它並從我的文件中取出我的參數。java套接字緩衝區和字符串
這裏我的代碼客戶端:
public static void transfert(InputStream in, OutputStream out) throws IOException{
PrintWriter printOut;
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!=-1)
out.write(buf,0,n);
printOut = new PrintWriter(out);
printOut.println("add");
System.out.println("envoie !!!");
printOut.println("1");
printOut.println("3");
// out.write(getBytes("add"),0,0);
printOut.flush();
}
,在這裏我的服務器代碼:
public static void transfert(InputStream in, OutputStream out, boolean closeOnExit) throws IOException
{
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!=-1)
out.write(buf,0,n);
buffIn = new BufferedReader (new InputStreamReader(in));
String nom_methode = buffIn.readLine();
String param1 = buffIn.readLine();
String param2 = buffIn.readLine();
System.out.println("methode:"+nom_methode+"param1:"+param1+"param2:"+param2);
if (closeOnExit)
{
in.close();
out.close();
}
}
編輯: 我還是很懷念的東西,現在我有我的線程錯誤,我認爲這個問題是從我的循環至極讀取我的文件輸入。 此外,實際上param仍然在我的文件中,而不是在我的參數...爲什麼循環不停止EOF後?
錯誤:
Exception in thread "Thread-0" java.lang.IndexOutOfBoundsException
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:318)
at serveurthread.AcceptClient.transfert(AcceptClient.java:45)
at serveurthread.AcceptClient.run(AcceptClient.java:84)
at java.lang.Thread.run(Thread.java:722)
client:
public static void transfert(InputStream in, OutputStream out) throws IOException{
PrintWriter printOut;
printOut = new PrintWriter(out);
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!=-1)
out.write(buf,0,n);
printOut.print('\u0004');
printOut.flush();
printOut.println("add");
System.out.println("envoie !!!");
printOut.println("1");
printOut.println("3");
// out.write(getBytes("add"),0,0);
printOut.flush();
}
服務器:
public static void transfert(InputStream in, OutputStream out, boolean closeOnExit) throws IOException
{
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!= (int)'\u0004'){
out.write(buf,0,n);
}
buffIn = new BufferedReader (new InputStreamReader(in));
String nom_methode = buffIn.readLine();
String param1 = buffIn.readLine();
String param2 = buffIn.readLine();
System.out.println("methode:"+nom_methode+"param1:"+param1+"param2:"+param2);
if (closeOnExit)
{
in.close();
out.close();
}
}
read(byte [])返回一個計數,而不是流中的字符。 -1 – EJP
我最終通過字符串發送所有內容,並將我的字符串文件更改爲我的服務器中的字節。 – user1904731