简体   繁体   English

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

[英]Java socket server only displays messages received after the connection closes

I am trying to write a code for a simple server, that receives messages from a client. 我正在尝试为一个简单的服务器编写代码,该服务器从客户端接收消息。 The connection is succesful but once the server connects with the client the messages are not displayed on the screen. 连接成功,但是服务器与客户端连接后,消息不会显示在屏幕上。 After I close the connection from the client side, the server receives all the messages in one go. 从客户端关闭连接后,服务器会一次性接收所有消息。

I need to receive the messages line by line because each line needs to de processed individually and in real time (I am using HMM for driver's actions recognition). 我需要逐行接收消息,因为每一行都需要分别实时地进行处理(我将HMM用于驾驶员的动作识别)。

Could someone tell me what am I doing wrong? 有人可以告诉我我在做什么错吗?

Thanko you very much. 非常感谢你。

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);
    }
}   

Client-side, do you flush your output stream ? 客户端,您是否刷新输出流?

When closing the connection, all remaining data are flushed but before that, they only are if there is enough "waiting" data to be sent. 关闭连接时,将清除所有剩余数据,但在此之前,只有在有足够的“等待”数据要发送时,它们才会被清除。

I managed to find a solution and I would like to share here. 我设法找到一个解决方案,我想在这里分享。

My client was a Visual Basic Application and I have a Java Server. 我的客户是一个Visual Basic应用程序,我有一个Java服务器。 The client was sending the messages without an End Of Line character so the entrada.readLine(); 客户端发送的消息没有行尾字符,因此entrada.readLine(); would be waiting for a signal that the message was over before displaying it (what never happened). 在显示该消息之前会一直等待该消息结束的信号(这从未发生过)。 The solution was to add a End Of Line character at the end of the client messages and everything worked out well in the end. 解决方案是在客户端消息的末尾添加行尾字符,最后一切都很好。

Thank you for the answers. 谢谢你的回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM