Socket inputStream read message giving an unexpected length

60 Views Asked by At

I have a function that reads a message from the client with a timeout of 100ms. In my code, I use this function in a loop until I get a string that is different than "" and that is how I know I got the message I needed and can continue my code. For some reason, it works for the first socket, but when I send what I received from socket to socket 2 and wait for socket2 to respond, I get bytesReceived = -1 even though socket2 is still connected and alive.

Code:

public String getMessage(int socketNumber) {
    Socket socket = socket1;
    if(socketNumber == 2){
        socket = socket2;
    }
    byte[] message = new byte[4096];
    int bytesReceived = 0;

    try {
        socket.setSoTimeout(100);
        bytesReceived = socket.getInputStream().read(message);
    } catch (SocketTimeoutException e) {
        return "";
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    System.out.println("AMOUNT OF BYTES RECEIVED FROM" + socketNumber + " IS " + bytesReceived);
    // Convert the message to a string.
    return new String(message, 0, bytesReceived);
}
1

There are 1 best solutions below

10
lance-java On

If a message is passed that is larger than your byte array, your code will not receive the whole message. Also, you might be better to wrap the InputStream in a Reader since some characters are two bytes and might be chopped in half between two read operations.

You could try something like:

Charset charset = Charset.forName("UTF-8");
Reader reader = new InputStreamReader(socket.getInputStream(), charset);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int count;
while ((count = in.read(buffer)) > 0) {
    builder.append(buffer, 0, count);
}
return builder.toString();