如何用socket_recvfrom读取套接字数据?

如何用socket_recvfrom读取套接字数据?

问题描述:

I need to get information from UDP socket, but the fact that i do not know how many answers will receive so i decided to wait for a few seconds. The main problem is that socket_recvfrom blocks and all the code stuck... Is there some way to wait for a few second and stop the socket?

My code:

$end_time = time() + 2;

while ($end_time > time()) {
    socket_recvfrom($socket, $buffer, 2500, 0, $from, $port);
    var_dump($buffer);
}

You can set the function to non blocking mode using the MSG_DONTWAIT flag:

$end_time = time() + 2;

while ($end_time > time()) {
    socket_recvfrom($socket, $buffer, 2500, 0, $from, $port, MSG_DONTWAIT);
    var_dump($buffer);
    // sleep 500ms to decrease cpu usage
    usleep(500000);
}