我正在尝试编写一个小程序,它打开一个服务器,创建一个连接到该服务器并从中接收消息的客户端。
这是到目前为止的代码
public static void main(String[] args) {
final ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(12345);
Thread t = new Thread(){
public void run(){
try {
Socket server = serverSocket.accept();
PrintWriter writer = new PrintWriter(server.getOutputStream(), true);
writer.write("Hello World");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
t.start();
Socket client = new Socket("localhost", 12345);
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String message = reader.readLine();
System.out.println("Received " + message);
} catch (IOException e1) {
e1.printStackTrace();
}
}
如果我运行程序,它会一直在 readLine() 中等待 - 很明显客户端没有收到来自服务器的消息。有谁知道为什么这不起作用?