Bob
Bob

Reputation: 91

Java socket BufferedReader read not reading

Im trying to make a client/server socket connection via BufferedReader and Buffered Writer, but reader not reading anything it is just hanged, where client send and flush properly. Server does not throw any exception as if client not sending anything to server.

My head is going go explode...

Im using same for both client and server:

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

Here is the code of server:

//inside of try catch
while(true){
          while(!in.ready())// just to debug
            System.out.println("READY: " + in.ready()); //just to debug
          System.out.println("READY: OK"); //just to debug
            msg = receive().toString(); //hangs here...
            System.out.println("KEYIS: " + msg);
           ///some stuff to do ....

public StringBuilder receive() throws IOException {
    StringBuilder str = new StringBuilder();
    int tmp;
    while(true){
        tmp = in.read();
        if(tmp == 0)
            break;
        else if(tmp == -1)
            throw new IOException();
        str.append((char)tmp);
    }
    return str;
}

Client code: not hanging here

 //inside of try catch
         send(KEY); //sended properly, no exception
         while(true){
             send(KEY); // sended properly, no exception
             System.out.println("sent");
             //System.out.println(receive().toString());
         }

public void send(String str) throws IOException{
    out.write(str + "\n"); //
    //out.newLine(); //tried too, not helped
    out.flush(); //push message to server
}

Upvotes: 3

Views: 2358

Answers (4)

Arashdeep Singh
Arashdeep Singh

Reputation: 320

    StringBuffer sb = new StringBuffer();
    int i;
    while ((i = bi.read()) != -1) {
        char c = (char) i;
        sb.append(c);
        
    }
    return sb.toString();

Upvotes: 1

Bob
Bob

Reputation: 91

Solved the problem... So stupid mistake... I just forgot to add a \0 to determine the end of message, so recieve method was waiting as if more data coming...

Upvotes: 0

user207421
user207421

Reputation: 310840

You're writing lines but you have a pretty pointless and elaborate and very buggy input method which doesn't actually read lines, and which throws the wrong exception at end of stream.

Try BufferedReader.readLine(), not forgetting to test for null.

Upvotes: 1

user4306951
user4306951

Reputation:

Well server waits for if(tmp == 0) which is 0 is a nil, and the client never sends it.
I think You are waiting about \n which it's not 0, it's 10(line feed).
Just wondered why don't you use DataOutputStream#writeUTF() and DataInputStream#readUTF()?

Upvotes: 2

Related Questions