Java套接字读取期间超时
如果通过 Socket
连接的客户端出现严重延迟,会发生什么情况? 假设我从 TCP 服务器调用 socket.read()
,客户端在网络管道上写入了一些内容,但他的连接延迟了 1 或 2 分钟。会发生什么? 读取
会失败吗?还是会等待?
我不确定这是否可能,但我正在 FICS 服务器上玩在线国际象棋,有时从我的角度来看似乎会发生这种情况(我只是这个国际象棋服务器的用户)。
我问这个问题是因为我正在开发一款在线游戏,我想以某种方式处理此类情况。但首先我需要知道是否:
- 它可能发生
- 它可以被检测到
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
read()
方法将会阻塞。但是有 < code>setSoTimeout()-方法,可用于设置可处理的超时。The
read()
-method will block. But there is thesetSoTimeout()
-method which can be used to set a timeout that can be handled.实际上,使用 setSoTimeout() 可能会有点误导。当您以这种方式使用它时:
构造函数启动 connect(),但尚未设置超时。您得到的不是预期的 3 秒超时,而是默认超时。要获得所需的超时,您可以按以下方式执行:
Actually, using
setSoTimeout()
might be a bit misleading. When you use it in such manner: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:
我建议不要仅仅依赖于设置
SO_TIMEOUT
变量,而是在客户端和服务器之间添加应用程序级心跳。如果客户端或服务器在指定时间内(例如,在心跳频率的两倍内)未收到心跳消息,则应断开连接,并在客户端的情况下尝试重新连接。使用心跳机制还允许您通过监视每一端接收心跳消息的延迟来测量延迟。
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.