Java socket timeout during read

2019-05-29 02:07发布

问题:

What happens if a client connected through a Socket has a bad lag ? Let's say i call socket.read() from the TCP server, and the client writes some stuff on the network pipe, but his connection is laging for 1 or 2 minutes. What will happen ? Will the read fail ? Or will it wait ?

I'm not sure if it's even possible, but i'm playing online chess on FICS server and sometimes it seems to happen from my point of view (I'm only a user of this chess server).

I'm asking this because i'm working on an online game and i'd like to handle such cases one way or another. But first I need to know if:

  • it can happen
  • it can be detected

Thanks

回答1:

I'd advise not relying solely on setting the SO_TIMEOUT variable but rather add application-level heartbeats between your client and server. If either the client or server does not receive a heartbeat message within a specified time (e.g. within twice the heartbeat frequency) it should sever the connection, and in the client's case attempt a reconnect.

Using a heartbeat mechanism also allows you to measure the lag by monitoring the delay in receiving heartbeat messages on each end.



回答2:

The read()-method will block. But there is the setSoTimeout()-method which can be used to set a timeout that can be handled.



回答3:

Actually, using setSoTimeout() might be a bit misleading. When you use it in such manner:

Socket sock = new Socket(host, port);
sock.setSoTimeout(3000); // 3 seconds timeout

The constructor initiates the connect(), while timeout haven't been set. Instead of expected 3 second timeout you get the default one. To get the desired timeout you can do it following way:

SocketAddress sockaddr = new InetSocketAddress(host, port);
Socket sock = new Socket();
sock.connect(sockaddr, 3000); // 3 seconds timeout