我是JAVA套接字的新手,我只想制作可接收一些字符串值的应用程序。我猜,服务器工作正常。它分别发送数据5次并停止。但是客户端不会分开接收服务器的消息,甚至更多, 当服务器停止客户端DONT时,客户端不停止并且仍接收消息(NULL)
服务器
static BufferedReader in;
static BufferedWriter out;
static Socket clientSocket;
public static void main(String[] args) {
try {
clientSocket = new Socket("192.168.0.106", 13130);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
int i = 0;
while (!clientSocket.isClosed()) {
System.out.println("Times: " + i++);
String cmd = in.readLine();
System.out.println(cmd);
}
clientSocket.close();
}catch (Exception e){
e.printStackTrace();
}
和服务器
void Write() throws Exception{
ServerSocket serverSocket;
serverSocket = new ServerSocket(13130);
Socket clientSocket;
System.out.println("Listening...");
clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// и отправлять
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
Thread.sleep(10000);
for (int i = 0; i < 5; i++) {
System.out.println("Times: " + i);
out.write("Hello " + i);
out.flush();
}
clientSocket.close();
serverSocket.close();
}
因此,我希望客户端读取数据5次并将停止。 但是我得到了下一个输出:
Times: 0
Hello 0Hello 1Hello 2Hello 3Hello 4
Times: 1
null
Times: 2
null
Times: 3
null
Times: 4
null
Times: 5
null
Times: 6
null
AND SO ON...
也许是问题:服务器发送消息的速度太快了?