ServerSocket 和socket 通信问题
我在写一个项目的时候,发现一个服务器端和客户端之间的通信问题,于是写了个小程序来测试,果然出现了问题.大家帮忙分析一下.
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerTest {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(5000);
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
byte [] buffer = new byte[200];
int len;
// len = is.read(buffer);
// System.out.println(new String(buffer,0,len));
while(-1!=(len = is.read(buffer,0,buffer.length))){
String str = new String (buffer,0,len);
System.out.println(str);
//break;
}
OutputStream os = socket.getOutputStream();
os.write("hello client! \n".getBytes());
os.close();
is.close();
ss.close();
}
}
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TcpClientTest {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1",5000);
OutputStream os = socket.getOutputStream();
os.write("hello Server ! \n".getBytes());
InputStream is = socket.getInputStream();
byte [] buffer = new byte[200];
int len;
// len = is.read(buffer);
// System.out.println(new String(buffer,0,len));
while(-1 != (len = is.read(buffer,0,buffer.length))){
String str = new String (buffer,0,len);
System.out.println(str);
//break;
}
os.close();
is.close();
socket.close();
}
}
加注释的地方是我后来测试的时候替换while循环的.
while(-1 != (len = is.read(buffer,0,buffer.length))){
String str = new String (buffer,0,len);
System.out.println(str);
}
直接替换成
len = is.read(buffer);
System.out.println(new String(buffer,0,len));
程序执行正确,或者说在while加入break;也可以正常执行,为什么只能读取一次,这在项目中肯定是不行的.不知道传过来的数据到底有多长,肯定需要while循环来读取.
死扛小王子
10 years, 6 months ago