使用 UDP 处理多个客户端
Handling multiple clients with UDP
想象一个 UDP 服务器:
while (true) {
try {
socket.receive(packet);
// handle packet (potentially CPU-intensive)
} catch (IOException e) {
e.printStackTrace();
}
}
困扰我的是我只有一个线程来处理来自所有客户端的所有数据包。我假设我的服务器不能启动多个线程来接收同一个套接字上的数据包?虽然我当然可以在单独的线程中处理数据包,但我仍然只有 1 个线程来接收数据包,无论将数据包转发到另一个线程所花费的时间有多短,它仍然是 window 服务器获胜的地方'听到传入的数据包。
所以我的问题是:如果服务器当前未在 server.receive()
中被阻止,发送到服务器的数据包会丢失,还是会在下次调用该方法时排队等待?如果他们迷路了,我该如何处理多个客户?
Do packets send to the server get lost if the server isn't currently blocked in server.receive()
没有
or do they get queued for the next time the method is called?
它们在套接字接收缓冲区中排队,如果有空间,否则它们将丢失。
how can I handle multiple client[s]?
要么以足够快的速度处理每个数据包以使套接字接收缓冲区永远不会溢出,要么启动一个新线程来处理每个数据报。
想象一个 UDP 服务器:
while (true) {
try {
socket.receive(packet);
// handle packet (potentially CPU-intensive)
} catch (IOException e) {
e.printStackTrace();
}
}
困扰我的是我只有一个线程来处理来自所有客户端的所有数据包。我假设我的服务器不能启动多个线程来接收同一个套接字上的数据包?虽然我当然可以在单独的线程中处理数据包,但我仍然只有 1 个线程来接收数据包,无论将数据包转发到另一个线程所花费的时间有多短,它仍然是 window 服务器获胜的地方'听到传入的数据包。
所以我的问题是:如果服务器当前未在 server.receive()
中被阻止,发送到服务器的数据包会丢失,还是会在下次调用该方法时排队等待?如果他们迷路了,我该如何处理多个客户?
Do packets send to the server get lost if the server isn't currently blocked in server.receive()
没有
or do they get queued for the next time the method is called?
它们在套接字接收缓冲区中排队,如果有空间,否则它们将丢失。
how can I handle multiple client[s]?
要么以足够快的速度处理每个数据包以使套接字接收缓冲区永远不会溢出,要么启动一个新线程来处理每个数据报。