我有以下服务器:
public final class Server implements Runnable {
private ServerSocket serverSocket;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
Server() {
Thread thread = new Thread(this);
thread.start();
}
@Override
public void run() {
boolean running = true;
try {
serverSocket = new ServerSocket(5000);
socket = serverSocket.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (running) {
String data = in.readLine();
System.out.println(data);
if (data.equals("quit")) {
running = false;
}
}
} catch (IOException e) {
System.err.println(e);
}
}
}
并关注客户:
public class Client {
private Socket socket;
private PrintWriter out;
public Client() {
socket = null;
try {
socket = new Socket("127.0.0.1", 5000);
out = new PrintWriter(socket.getOutputStream());
} catch (final UnknownHostException e) {
System.err.println("Address unknown "
+ e.getMessage());
} catch (final IOException e) {
System.err.println("Error connecting to the Server "
+ e.getMessage());
}
}
public void sendMessage(String msg) {
out.println(msg);
}
}
我能够建立初始连接,但只要执行sendMessage()
方法,服务器就不会打印任何内容。你知道为什么我收不到消息吗?
答案 0 :(得分:3)
当客户端使用in.readLine()
打印时,服务器使用print()
进行读取(无新行)。所以服务器正在等待出现从未发生的新行。
尝试在客户端使用println()
进行书写。
此外,您需要刷新您的作者:添加out.flush()
。这是使编写器实际发送其有效负载所必需的。