[英]java socket buffer and string
對於一門功課我嘗試發送一個文件,對應於該文件中的一些參數。 所以,我發送我的文件,並在我的字符串之后。 問題是我的參數進入我的文件,而不是我的變量。 我理解了這個問題,只要他收到一些東西,我的循環就繼續寫入文件,但是我想停止它,並讓我的參數不在文件外。
這是我的代碼客戶端:
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();
}
}
編輯:我仍然想念一些東西,現在我的線程有錯誤,我認為問題出在我的循環中,它在輸入中讀取了我的文件。 而且,實際上參數仍然存在於我的文件中而不是我的參數中……為什么循環在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();
}
}
您將需要在流中使用某種標記來指示文件結束。 我建議使用'\'
這是EOF字符。 基本上,在寫入文件后寫入此字符,然后像這樣調整服務器中的循環:
while((n=in.read(buf))!=(int)'\u0004')
out.write(buf,0,n);
現在,服務器在必要時停止讀取文件,然后可以四處讀取字符串。
同樣, read
返回讀取的字節數,而不是char。 通過聲明字節而不是字節數組,我一次可以傳遞一個字節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.