作者:xwsk008 | 来源:互联网 | 2023-06-11 08:20
webSocketServer 接受到消息后广播但是每次都是指发送给当前 消息推送的对象求解?服务端代码如下:123456789101112131415161718192021222324252627
webSocketServer 接受到消息后广播但是每次都是指发送给当前 消息推送的对象求解?
服务端代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| protected function execute(Input $input, Output $output)
{
$this->server = new \swoole_websocket_server('0.0.0.0', 10000);
$this->server->set([
/**
* 设置启动的worker进程数
* 业务代码是全异步非阻塞的,这里设置为CPU的1-4倍最合理
* 业务代码为同步阻塞,需要根据请求响应时间和系统负载来调整
*/
'worker_num' => 4,
// 守护进程化
'daemonize' => false,
// 监听队列的长度
'backlog' => 128
]);
$this->server->on('Open', [$this, 'onOpen']);
$this->server->on('Message', [$this, 'onMessage']);
$this->server->on('Close', [$this, 'onClose']);
$this->server->start();
}
public function onOpen(\swoole_websocket_server $server, \swoole_http_request $request)
{
echo "server: handshake success with fd{$request->fd}\n";
}
// 收到数据时回调函数
public function onMessage(\swoole_websocket_server $server, \swoole_websocket_frame $frame)
{
//echo sizeof($server->connections);
//echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
foreach ($server->connections as $fd) {
echo "push data to".$fd."\n";
//$this->server->push($fd,$frame->data);
}
}
// 连接关闭时回调函数
public function onClose($server, $fd)
{
echo "client {$fd} closed\n";
} |
服务端运行记录
server: handshake success with fd1 //客户端1连接服务器
push data to1 //推送给1消息正确
server: handshake success with fd2 //客户端2连接服务器
push data to2 //推送给2消息,客户端1没了
但是如果加上 sizeof($server->connections)又发现他确实有两个对象
请问咋回事