Websocket -- PHP Push Data
I'm running this loop on the server side:
while (true) {
$changed = $this->sockets;
socket_select($changed, $write = NULL, $except = NULL, NULL);
foreach($changed AS $socket) {
if($socket == $this->master) {
$client = socket_accept($this->master);
if($client < 0) {
echo "socket_accept failed";
continue;
} else {
$this->connect($client);
}
} else {
$bytes = @socket_recv($socket, $buffer, 2048, 0);
if($bytes == 0) {
$this->close($socket);
} else {
$user = $this->get_user_by_socket($socket);
if(!$user->handshake) {
$this->do_handshake($user, $buffer);
} el开发者_Go百科se {
$this->process($user, $buffer);
}
}
}
}
}
Basically it waits for anything to be changed within the sockets before performing any actions that can be sent to all clients, or just individual clients. What I would like to do is be able to push data to clients after a period of inactivity...say like a countdown timer in a game. So after 5 seconds if there has been no action from a user, automatically send an action for that user. How would I go about that? I've tried to have a last_update with the time() stored in it then check the math, but anything that I put within the while(true) loop only gets run when there is a change in the sockets, which comes from the user end...
I guess I'm just super lost. :)
Thanks!
You need to set a non-blocking flag for your socket_recv() function. Otherwise it will just sit on this line until a minimum number of bytes have been received.
Perhaps
$bytes = socket_recv($socket, $buffer, 2048, MSG_DONTWAIT);
精彩评论