Search code examples
javacsocketsreadlineforum

Socket (C/Java) BufferedReader readLine() doesn't stop


I'm creating a forum with a Java interface and a C server.

I have trouble sending a message from C to Java....

I created a socket (named "socket") that works, like this :

socket = new Socket(adr, port);
//adr and port are defined before

But when doing this on the Java:

String str =null;
try {
    BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream()) );
    while ((str=br.readLine()) != null && str.length()>0)
    {
        System.out.println("str = " + str);
    }
        br.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

It just can't receive the message from the server. It only shows the message when I brutally close the C server.

Here is how the server sends the message through the Socket :

write(client_sock,"0\0",strlen("0\0"));

I have no idea how to receive this "0" without closing the server. Any ideas ?


Solution

  • readLine() has read the send data, but blocks until a line feed or carriage return was read
    If your client sees the data only if you are closing the server, than your server never sends a line feed or a carriage return.
    Assuming, you want to send a file line by line to the client(example in java, it is my main language):

    Socket client = server.accept();
    OutputStream os = client.getOutputStream();
    
    BufferedReader br = new BufferedReader( new InputStreamReader(Files.newInputStream(file.toPath())));
    String str;
    while ((str = br.readLine()) != null && str.length() > 0) {
         os.write((str).getBytes());
    }
    br.close();
    os.close();
    

    As you can see, the server don't sends a line feed or carriage return. These were removed by readLine()!
    So, the readLine() on your clientside is blocking until the socket will closed.

    If you change the write instruction in that way:

    os.write((str+"\n").getBytes());
    

    your client is able to read the lines, even if the server is still writing the following lines.