The PHP manual entry on socket_read() is a little vague when it comes to how much (if any) internal buffering it's doing. Given that you are passing 1024 in for the length, that specifies that it should return after receiving no more than 1024 bytes of data.
关于socket_read()的PHP手册输入有点模糊,当涉及它正在做多少(如果有的话)内部缓冲时。鉴于您正在传入1024 in的长度,这指定它应该在接收不超过1024个字节的数据后返回。
Disclaimer: the following is just speculation, as I have no knowledge of the internal implementation of socket_read().
免责声明:以下只是推测,因为我不了解socket_read()的内部实现。
If the socket_read() function is using its length parameter as a hint for an internal buffer size, you might see bad performance with small UDP packets. For example, if socket_read() waits for 1024 bytes of data regardless of the size of the packets, if you are constantly receiving 60 byte UDP packets it'll take a while for the buffer to fill and the function to return.
如果socket_read()函数使用其length参数作为内部缓冲区大小的提示,则可能会发现使用小UDP数据包时性能较差。例如,如果socket_read()等待1024字节的数据,而不管数据包的大小如何,如果您经常接收60字节的UDP数据包,则缓冲区需要一段时间才能填充并返回函数。
(Note: after looking up the "unread_bytes" field mentioned by Tim, it looks like PHP does keep internal buffers, but it makes no mention of how large or small those might be.)
(注意:在查找Tim提到的“unread_bytes”字段后,看起来PHP确实保留了内部缓冲区,但它没有提到它们可能有多大或多小。)
In this case, socket_read() will return larger chunks of data once its buffers fill to reduce processing resource consumption, but at the expense of higher latency. If you need the packets as past as possible, perhaps setting a lower length field would work. That would force socket_read() to return sooner, albeit at the expense of executing your loop more often. Also if you set the length too low, your socket_read()'s might start returning incomplete packets, so you'll have to account for that in your code. (If that matters for your application, of course.)
在这种情况下,一旦缓冲区填充,socket_read()将返回更大的数据块,以减少处理资源消耗,但代价是延迟更高。如果您需要尽可能多的数据包,可能会设置较低的长度字段。这将迫使socket_read()更快地返回,尽管代价是更频繁地执行循环。此外,如果您将长度设置得太低,您的socket_read()可能会开始返回不完整的数据包,因此您必须在代码中考虑该数据包。 (当然,如果这对您的申请很重要。)