Read Data from a Java Socket

前端 未结 4 1409
被撕碎了的回忆
被撕碎了的回忆 2021-01-05 13:53

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.



        
相关标签:
4条回答
  • 2021-01-05 14:06

    For me this code is strange:

    bis.readLine()
    

    As I remember, this will try to read into a buffer until he founds a '\n'. But what if is never sent?

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

    int bytesExpected = clientSocket.available(); //it is waiting here
    
    int[] buffer = new int[bytesExpected];
    
    int readCount = clientSocket.read(buffer);
    

    You should add the verifications for error and interruptions handling too. With webservices results this is what worked for me ( 2-10MB was the max result, what I have sent)

    0 讨论(0)
  • 2021-01-05 14:22

    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 讨论(0)
  • 2021-01-05 14:26

    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();
    
    0 讨论(0)
  • 2021-01-05 14:30

    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).

    0 讨论(0)
提交回复
热议问题