简体   繁体   中英

On receiving a data from the server it is displayed/received after closing the socket. How to receive it immediately once the server sends.?

I am sending a data from the server to client, but the client receives it only at the time of disconnect. But i need it as soon as the server sends. I dont know why it is sending the data late after the socket connection closes.

public void run() {
                try {
                    socket = new Socket(eHostIp.getText().toString(), Integer.parseInt( eHostPort.getText().toString() ) );


                    BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ), 1024 );
                    eReceiveData.setText( "Server Connected... XXXXXXX" );
                    String line;
                    while ((line = in.readLine()) != null) {
                        Log.d("read line",line);
                        eReceiveData.setText( line );
                        socket.setSoTimeout( 1000 );
                       //socket.close();
                    }

                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } );
        thread.start();
    }

Check that your server sends an EOL character at the end of each message such that your BufferedReader can use the readline() method properly.

Alternatively you can try to force flush() after each message as well.

This saved my day...REading the line as a character (line += (char)in.read())

                String line = " ";
                while ((line += (char)in.read()) != null) {
                    Log.i( "read line", line );
                    eReceiveData.setText( line );

                }

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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