Reading data from a Java socket

I have a Socket listening on some kind of port x.

I can send data to a socket from my client application, but could not get a response from the server socket.

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

.. This piece of code reads data from the server.

But I can not read anything from the server until the Socket on the server is closed. The server code is not under my control to edit anything on it.

How can I overcome this from client code.

thank

+3
source share
4 answers

For communication between the client and the server, the protocol must be clearly defined.

, , . , -, . , , , , , EOL. , readLine() , , . readLine(), . , ( ).

+5

, ( , readLine()). -, . , :

    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();
+10

:

bis.readLine()

As I recall, it will try to read into the buffer until it finds it '\n'. But what if it never sets off?

My ugly version violates any design pattern and other recommendations, but it always works:

int bytesExpected = clientSocket.available(); //it is waiting here

int[] buffer = new int[bytesExpected];

int readCount = clientSocket.read(buffer);

You should also add checks to handle errors and interrupts. With webservices results, this is what worked for me (2-10 MB was the maximum result that I sent)

+1
source

Here is my implementation

 clientSocket = new Socket(config.serverAddress, config.portNumber);
 BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

  while (clientSocket.isConnected()) {
    data = in.readLine();

    if (data != null) {
        logger.debug("data: {}", data);
    } 
}
0
source

Source: https://habr.com/ru/post/1652292/


All Articles