我正在编写一个 Java 客户端/服务器应用程序。它应该允许客户端向服务器发送文本数据。这种通信应该可以使用同一个连接重复多次。
我这样写:
// On a server:
ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
socket.setKeepAlive(true);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if (reader.ready()) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
// do something with line
}
}
// On a client:
Socket socket = new Socket(host, port);
socket.setKeepAlive(true);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("Some data from client to server");
writer.flush();
问题是:在客户端关闭 OutputStream 之前,我无法在服务器上读取。或者,如果它已经关闭,我无法再次在客户端上打开 OutputStream。如何连续发送和读取数据?