我已經寫客戶端 - 服務器消息發送使用Java,它工作正常套接字程序,但如果前一消息的字符串長度比本in.read(b5)
越大,印刷有先前的消息字符串的消息添加到它的字符。這個問題是由於以前存儲在字節數組中的字符。CLIENT -server套接字編程
如何清除每個循環的字節數組? 我該如何解決這個問題?
客戶端代碼:
try
{
String add=args[0];
int port=Integer.parseInt(args[1]);
Socket s=new Socket(add,port);
OutputStream out=s.getOutputStream();
InputStream in=s.getInputStream();
BufferedReader bufIn = new BufferedReader(new InputStreamReader(in));
BufferedWriter bufOut = new BufferedWriter(new OutputStreamWriter(out));
byte b1[]=new byte[100];
byte b2[]=new byte[100];
while(true)//infinite loop
{
System.out.println("To Server:");
System.in.read(b1); //reading from keyboard
out.write(b1); //writing to server
in.read(b2); //reading from server
String s1=new String(b2);
String s2=s1.trim();
System.out.println("From Server:"+s2);
}
}
catch (Exception e)
{
System.err.println(e);
}
服務器代碼:
try
{
int port=Integer.parseInt(args[0]);
ServerSocket ss=new ServerSocket(port);
while(true) //this loop for diff. no. of clients
{
Socket s=ss.accept();
InputStream in=s.getInputStream();
OutputStream out=s.getOutputStream();
byte b1[]=new byte[100];
byte b2[]=new byte[100];
while(true) //this loop for one client diff. no. of times.
{
in.read(b1);
String s1=new String(b1);
String s2=s1.trim();
System.out.println("From Client:"+s2);
System.out.print("To Client:");
System.in.read(b2);
out.write(b2);
}
}
}
catch (Exception e)
{
System.err.println(e);
}
在調用read之前清空b2也許'Arrays.fill(b2,0);'你如何表示空字符? –
我添加了Arrays.fill(b2,0);但得到了一個方法填充未找到錯誤...我認爲b2必須是一個字節數組ri8 ?? ?? @JerryJeremiah – user3021254