Cannot send and receive data using BufferedReader/

2019-02-26 14:30发布

问题:

I am making a client-server application and am using the following code for the exchange of data b/w the server and clients.

Server's send and receive code:

public void run() {
     try {
        BufferedReader input = new BufferedReader(new InputStreamReader(socketNew.getInputStream()));
        String message=input.readLine();
        while(message.length()!=0)
        {
            for(Socket s:socs) //socs is a list containing all the connected sockets
            {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                writer.write(message);
            }
        }

     } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

  }

Client's send method:

private void send_data() {

    BufferedWriter writer;
    try {
        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        writer.write(this.name+textField.getText());
        textField.setText("");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Client's receive method:

public  void receive_data(){
    BufferedReader input;
    try {
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String message=input.readLine();
        while(message.length()!=0)
        {console(message);}
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

I am not having any data exchange b/w the server and the clients.Can someone help me please?

回答1:

You are suffering from buffering: message is written in a buffer and probably never sent. Flush the writer to ensure it sends data:

    writer.write(...);
    writer.flush();

Also, BufferedReader.readLine reads lines. Lines have to be terminated with a line break, such as \n. It's not clear if you are sending line breaks.

Also, this is an infinite loop:

    String message=input.readLine();
    while(message.length()!=0) {
        /* code that does not modify message */
    }


回答2:

Don't keep creating new readers and writers. Use the same ones for the life of the socket. You're losing data in the old BufferedReader that is being discarded. These buffered things, err, buffer.

Also this:

String message=input.readLine();
while(message.length()!=0)

is, err, nonsense. Firstly you're not checking message for null, so you're going to get a NullPointerException at end of stream. Secondly, you aren't doing any further input inside the loop so if it doesn't throw NPE and the message isn't zero length it will loop forever.