一个套接字上有多个 UDP 数据包
假设我有一个带有多个客户端(UDP)的服务器。每当服务器收到客户端发来的数据包时,服务器都会花 1 秒的时间处理该数据包,并在处理后立即向所有客户端发送新的数据包。
如果 0.1 秒内有 10 个数据包到达,服务器能够做到这一点吗?换句话说,是否能够在处理完第一个收到的数据包后立即向每个客户端发送新的数据包? (我感觉套接字会被其他 9 个未读数据包“堵塞”)
服务器循环将如下所示:
while (1) {
read_a_packet()
process_packet()
send_new_packet_to_all_clients()
}
Suppose I have a server with multiple clients (UDP). Whenever it receives a packet from a client, the server will spend 1 second processing the packet and send out that a new packet to all clients immediately after processing.
Will the server be able to do this if 10 packets arrive within 0.1 seconds? In other words, is it able to send out a new packet to each client immediately after processing the first received packet? (I have the feeling that the socket would get "clogged" up by the 9 other unread packets)
The server loop would be like:
while (1) {
read_a_packet()
process_packet()
send_new_packet_to_all_clients()
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
传入的 UDP 数据包被放入缓冲区以供将来检索。如果您的处理速度足够慢,足以用数据包填充套接字缓冲区,则后续数据包将被丢弃。
另请参阅 Linux 套接字缓冲区如何溢出? 和 C++ UDP 套接字数据包队列(另请查看那里的评论)。
Incoming UDP packets are put into buffer for future retrieval. If your processing is slow enough to fill the socket buffer with packets, following packets will just be discarded.
See also How does a Linux socket buffer overflow? and C++ UDP sockets packet queuing (also check out comments there).
根据您自己的定义,
process_packet()
需要 1 秒才能运行。一个线程一次只能做一件事,因此单线程中这样的循环服务器将花费 10 秒来处理 10 个数据包。因此,要么将 process_packet() 速度加快到不到 1 秒,要么运行多个处理线程,以便可以并行处理多个数据包。By your own definition,
process_packet()
takes 1 second to run. A thread can only do one thing at a time, so such a looping server in a single thread will take 10 seconds to process 10 packets. So either speed upprocess_packet()
to less then 1 second, or else run multiple processing threads so you can process multiple packets in parallel.