Java套接字服务器仅显示连接关闭后收到的消息

时间:2016-09-07 11:16:27

标签: java sockets tcp server message

我正在尝试为一个简单的服务器编写代码,该服务器从客户端接收消息。连接成功,但一旦服务器与客户端连接,消息就不会显示在屏幕上。从客户端关闭连接后,服务器一次性收到所有消息。

我需要逐行接收消息,因为每行需要单独和实时处理(我使用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);
    }
}   

2 个答案:

答案 0 :(得分:1)

客户端,您是否刷新输出流?

关闭连接时,所有剩余数据都会被刷新,但在此之前,只有在有足够的"等待"要发送的数据。

答案 1 :(得分:0)

我设法找到了解决方案,我想在此分享。

我的客户端是一个Visual Basic应用程序,我有一个Java服务器。客户端发送的消息没有End Of Line字符,因此entrada.readLine();将在显示消息之前等待消息已经结束的信号(从未发生过)。 解决方案是在客户端消息的末尾添加End Of Line字符,最后一切都很顺利。

感谢您的回答。

相关问题