Well, this should be a rookie-level problem, but I can't even read the documentation.
Reply content:
Well, this should be a rookie-level problem, but I can't even read the documentation.
The socket for PHP is a resource type:
Resource (4) of type (socket), which is what each Socket handle looks like:
and the Linux C socket FD is an int integer, each of which is a different number.
Native PHP do not "active to already connected, the user uid=123 the user, push a message",
But with Swoole using the socket of Linux C, we can implement "active to the user who is already connected, the user uid=123, push a message".
Here we can use the simplest share memory of System V to share data IPC between processes, maintaining a mapping table for the user ID and its socket connection.
The code is as follows:
Set (Array (' worker_num ' = 8,//number of worker processes ' daemonize ' = = false,//whether as daemon)); $shmid = Shm_attach (Getmypid (), 10 24*66); # Allocate 66kB for shared memorydefine ("Shared_uid_connection_map"), Shm_put_var ($shmid, Shared_uid_connection_ MAP, []); $serv->on (' Connect ', function ($serv, $FD) use ($shmid) {echo "client:connect.\n";}); $serv->on (' Receive ', function ($serv, $FD, $from _id, $data) use ($shmid) {$serv->send ($fd, ' swoole: '. $data); $serv->close ($FD); $trimdata = Trim ($data); if ($trimdata = = ' I am lucky man ') {$map = Shm_get_var ($shmid, Shared_uid_connection_map); $map [] = $FD; # $map [$uidFromData] = $FD; Shm_put_var ($shmid, Shared_uid_connection_map, $map); } if ($trimdata = = ' Broadcast to Lucky Man ') {$map = Shm_get_var ($shmid, Shared_uid_connection_map); Var_dump ($MAP); $ $map is an array whose valuse is int $fd foreach ($map as $FD) {$serv->send ($FD, "some body broadcast To youLuck Man "); }} # Broadcast to all users//$start _FD = 0; while (true)//{//$conn _list = $serv->connection_list ($start _fd, 10); if ($conn _list===false or Count ($conn _list) = = = 0)//{//echo "finish\n"; Break }//$start _FD = end ($conn _list); Var_dump ($conn _list); foreach ($conn _list as $FD)//{//$serv->send ($FD, "broadcast"); }//}//Var_dump ($serv->connections); foreach ($serv->connections as $k + = $v) {//$lk = [$k, $v]; Var_dump ($LK); }); $serv->on (' Close ', function ($serv, $FD) {echo "client:close.\n";}); $serv->start ();
Then can open n client, to test the code, such as I open 3 telnet 127.0.0.1 1024, the last message to the server "I am lucky Man", the first to the server "broadcast to Lucky Man", then the third will receive "Some body broadcast to you luck Man", implements sending messages to specific users.
It's so simple,
Swoole Dafa Good, asynchronous io+ multi-process is also the most mature outcome scheme (salute Nginx)
Ha ha haha
UID is only the UID you identify, the socket link to the service, there is a unique ID, you want to send a message to the client only through this unique ID, you can do a mapping between the two, then you can.