zored
zored

Reputation: 3064

BufferReader unexpected behavour

I'm trying to read data from socket using threading run method:

@Override
public void run() {
    while(true){
        try{
            String o = "";
            socketServer = new ServerSocket(port);
            System.out.println("Waiting for connection on port "+port+".");
            Socket socket = new Socket();
            socket = socketServer.accept();
            System.out.println("Connection got.");
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            int c;
            while(( c = input.read()) != -1)
                o += (char)c;
            PrintWriter output = new PrintWriter(socket.getOutputStream());
            output.println("ok");
            output.flush();
            output.close();
            input.close();
            socket.close();
            socketServer.close();
            textFieldMessage.setText("Сообщение от "+socket.getInetAddress().getCanonicalHostName()+":\n"+o);
        }catch(Exception e){
            e.printStackTrace();
            System.exit(-1);
        }

    }
}

But it's stucked on while loop. Debugger told that there was no -1 value at the end. What's wrong here?

Upvotes: 1

Views: 137

Answers (3)

user207421
user207421

Reputation: 310860

The peer isn't closing the socket, so you are never getting the -1, so you are blocking in the read() invocation after the last character received. Your strategy is flawed. You are reading to EOS and then expecting to be able to write a reply. Unless the peer shuts down his socket for output and then reads, this is never going to work. You need to define your application protocol properly. At present you are expecting the peer to do write/close/read. Doesn't make sense.

Upvotes: 1

sakthisundar
sakthisundar

Reputation: 3288

read() method of InputStream blocks until the data is available.

It can return -1 only when the end of the stream is detected.(Though it shouldn't be the case with sockets) So while loop will block if the data is not available i.e your read call will wait for the data to be read.

Note :

But if the value is -1, your program should have exited. So what are you reading ?

Upvotes: 1

Jon Lin
Jon Lin

Reputation: 143856

Because you're reading from a Socket, you'll never reach the end of the stream unless the socket or stream has been closed. So the while loop will block on input.read() because it won't return -1 until the client closes the stream/socket.

Not really sure what it is you are reading from the socket, but you could try using the BufferedReader's readLine() method. You can either know how many lines you need to read ahead of time, or end the reading with a blank line (like HTTP).

Upvotes: 1

Related Questions