简体   繁体   中英

Java - client receiving a null response from in.readLine()

I'm a long way into writing a card game that allows people to play online against each other. During testing I've noticed that clients are very occasionally getting a null response to their messages and I don't know why.

Client code:

InetAddress address = InetAddress.getByName(SERVER_IP);
Socket socket = new Socket(address, SERVER_PORT_NUMBER);
socket.setSoTimeout(20000);

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.write(messageString + "\n");
out.flush();

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
responseString = in.readLine();

//new handling I've added since getting NullPointers later on
if (responseString == null)
{
    retryOrStackTrace(new Throwable("NULL responseString"));
}

Server code:

BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
message = in.readLine();
String response = getResponseForMessage(message);

//Sometimes getting a null response client-side
if (response == null)
{
    Debug.stackTraceServerWithReason("About to send NULL response for message " + message);
}

BufferedOutputStream os = new BufferedOutputStream(clientSocket.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
osw.write(response + "\n");
osw.flush();
osw.close();

The server-side stack trace hasn't come out since I added it so it definitely isn't a problem with the server building a response.

Due to how intermittent this is I want to put it down to connectivity, but I've had it when running the server on the same box and pointing the client at localhost so I'm not sure. I'd also expect any connection issues to be covered by ConnectException/SocketException/SocketTimeoutException, all of which the client already catches before using retryOrStackTrace() to resend the message a certain number of times before giving up.

I can leave things as they are and let the null responses be handled in the same way but it feels lazy. I just don't know where to start in figuring out what the underlying issue is here.

Looking back at this I believe the issue was around breakpointing/hotswapping code by building in Eclipse. I only ever saw this problem when running through Eclipse - running through a JAR works fine. D'oh!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM