我的意思是,你的解决方案会起作用,但我看不出你不能使用稍微多一点的带内控制机制的原因。试试这个,服务器上只有一个套接字:
List connections contains pairs (client, lastPacketTime)
Socket is a single UDP Socket
Thread 1 Loop:
Get new UDP Datagram P From Socket
If P.client in List:
update lastPacketTime
Else:
add P.client to list
If P is not Ping datagram:
Do other operations on P
Thread 2 Loop:
For client in List with lastPacket time 3-10 Seconds ago:
send ping request via Socket
For client in List with lastPacket time > 10 Seconds ago:
Mark client as down.
Sleep for some time
这在客户端:
Loop:
If I have data to send:
Send it!
Else if I have a ping request in my UDP Socket:
Send Ping datagram
Else
Sleep for some time.
如果您需要比这更可靠的握手,您可以考虑在 UDP 内容旁边打开与服务器的 TCP 连接。然后服务器可以使用 TCP 连接来检查活跃度。老实说,当人们尝试进行面向连接的 UDP 时,我脖子后面的头发都竖起来了。如果您担心 ping 时间的所有处理和更新,您可以添加第三个线程:
List contains pairs (client, lastPacketTime)
Queue contains Datagrams with time updates.
Socket is a single UDP Socket
Thread 1 Loop:
Get new UDP Datagram P from Socket
Add P to Queue
If P is not Ping datagram:
Do other operations on P
Thread 2 Loop:
Get new Datagram P from Queue
If P.client in List:
update lastPacketTime
Else:
add P.client to list
Thread 3 Loop:
For client in List with lastPacket time 3-10 Seconds ago:
send ping request via Socket
For client in List with lastPacket time > 10 Seconds ago:
Mark client as down.
Sleep for some time