Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Data from a Java Socket

Tags:

java

tcp

sockets

I have a Socket listening on some x port.

I can send the data to the socket from my client app but unable to get any response from the server socket.

  BufferedReader bis = new BufferedReader(new 
  InputStreamReader(clientSocket.getInputStream()));
  String inputLine;
  while ((inputLine = bis.readLine()) != null)
  {
      instr.append(inputLine);    
  }

.. This code part reads data from server.

But I cant read anything from server until unless the Socket on the server is closed. Server code is not under my control to edit something on it.

How can I overcome this from client code.

Thanks

like image 903
Suave Nti Avatar asked May 17 '13 12:05

Suave Nti


People also ask

How do you read socket data?

Reading Binary Data from a Socket The simplest protocol which we can define is called TLV (Type Length Value). It means that every message written to the socket is in the form of the Type Length Value. So we define every message sent as: A 1 byte character that represents the data type, like s for String.

What is difference between socket () and ServerSocket () class?

Here, two classes are being used: Socket and ServerSocket. The Socket class is used to communicate client and server. Through this class, we can read and write message. The ServerSocket class is used at server-side.


2 Answers

Looks like the server may not be sending newline characters (which is what the readLine() is looking for). Try something that does not rely on that. Here's an example that uses the buffer approach:

    Socket clientSocket = new Socket("www.google.com", 80);
    InputStream is = clientSocket.getInputStream();
    PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());
    pw.println("GET / HTTP/1.0");
    pw.println();
    pw.flush();
    byte[] buffer = new byte[1024];
    int read;
    while((read = is.read(buffer)) != -1) {
        String output = new String(buffer, 0, read);
        System.out.print(output);
        System.out.flush();
    };
    clientSocket.close();
like image 113
ashatch Avatar answered Oct 21 '22 20:10

ashatch


To communicate between a client and a server, a protocol needs to be well defined.

The client code blocks until a line is received from the server, or the socket is closed. You said that you only receive something once the socket is closed. So it probably means that the server doesn't send lines of text ended by an EOL character. The readLine() method thus blocks until such a character is found in the stream, or the socket is closed. Don't use readLine() if the server doesn't send lines. Use the method appropriate for the defined protocol (which we don't know).

like image 26
JB Nizet Avatar answered Oct 21 '22 19:10

JB Nizet