php - Send message via socket to a specific client with PHP Socket.IO
问题描述
I need to send a message to a client connected to a socket server but I need it to only be sent to a person, and not a broadcast as such. I have read that with the function to()
of socket.IO it can be but I have implemented it in several ways and I do not get it, I send it to all.
this is my code
... $socket->on('new message', function($message) use($socket) { $socket->emit("new message", array( "username" => $socket->username, "action" => "me", "message" => [ "from" => $socket->username['WP_USER_DATA']['guid'], "type" => "user", "time" => date('H:i'), "message" => $message ] ) ); //I NEED HELP HERE, PLEASE $socket->broadcast->emit("new message", array( "username" => $socket->username, "action" => "chat", "message" => [ "from" => $socket->username['WP_USER_DATA']['guid'], "type" => "", "time" => date('H:i'), "message" => $message ] )); }); ...
解决方案
From the Socket.IO cheatsheet:
// sending to individual socketid (private message)
io.to(`${socketId}`).emit('hey', 'I just met you');
So for you, it's something like:
//I NEED HELP HERE, PLEASE
io->to($socketId)->emit("new message", array(
"username" => $socket->username,
"action" => "chat",
"message" => [ "from" => $socket->username['WP_USER_DATA']['guid'], "type" => "", "time" => date('H:i'), "message" => $message ]
));
Note: you need to store (in array
) the ids ($socket->id
) of the clients when they connected, and use the one you need as $socketId
in the example above.
推荐阅读
- javascript - 在移动版本上禁用外部脚本
- r - 通过闪亮服务器中的接收器功能保存文件?
- node.js - 短时间内 Node.js Azure webapp 出现 404 错误
- c++ - 将互斥引用从主传递到类
- google-api - Google Cloud Storage API 写入限制
- sql - varchar2 字符串转日期格式
- c++ - Is accessing accessing a child attribute in the parent constructor UB when using CTRP?
- excel - VBA Excel - 如何将日期字符串从 dd/mm/yyyy 转换为 yyyy-mm-dd?
- angular - 接口,如何定义默认值
- c# - EF Core 多对多关系复合键创建显示无效的属性表达式