最近我一直在研究套接字通信,在我阅读了一些教程后,我发现了类似的内容。
public class Server{
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket server = new ServerSocket(9999);
Socket socket = server.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = "";
int ch = -1;
while((ch=in.read())!= -1 ){
message+=ch;
}
// String message = in.readLine();
System.out.println("RECEIVED "+message);
out.write("RESPONSE "+message+"\n");
out.flush();
System.out.println("NEW MESSAGE SEND");
Thread.sleep(3000);
System.out.println("CLOSE");
server.close();
}
}
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("127.0.0.1", 9999);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.write("MESSAGE\n");
out.flush();
System.out.println("SEND MESSAGE");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(in.readLine());
socket.close();
}
}
运行此代码后,Client
会在服务器挂起"SEND MESSAGE"
时记录in.read()
,并且不会收到任何消息。
任何人都可以帮我解释一下我做错了什么吗?
答案 0 :(得分:3)
您的服务器正在从套接字读取,直到流结束。仅当对等方关闭连接时才会发生流结束。此时您将无法发送回复。您需要重新考虑您的协议。举个简单的例子,你可以像在客户端一样一次一个地读写行。