我正在尝试编写简单服务器的代码,该服务器接收来自客户端的消息。连接成功,但是一旦服务器连接到客户端,消息就不会显示在屏幕上。在关闭客户端的连接后,服务器一次接收所有消息。Java套接字服务器仅显示连接关闭后收到的消息
我需要逐行接收消息,因为每一行都需要单独实时处理(我正在使用HMM进行驱动程序的动作识别)。
有人能告诉我我做错了什么吗?
非常感谢您。
public static void main(String args[]) {
ServerSocket my_server = null;
String received_message;
DataOutputStream output = null;
Socket socket_connected = null;
try {
my_server = new ServerSocket(9090);
}
catch (IOException excepcion) {
System.out.println(excepcion);
}
try {
socket_connected = my_server.accept();
BufferedReader entrada = null;
while (socket_connected.isConnected() == true){
entrada = new BufferedReader(new InputStreamReader(socket_connected.getInputStream()));
output = new DataOutputStream(socket_connected.getOutputStream());
System.out.println("Confirmando conexion al cliente....");
received_message = entrada.readLine();
System.out.println(received_message);
entrada.close();
output.close();
}
socket_connected.close();
}
catch (IOException excepcion) {
System.out.println(excepcion);
}
}
你知道'flush'方法吗?您可以在套接字(客户端或服务器端)写入后使用它 –