雅安论坛
标题:
SWOOLE相关知识
[打印本页]
作者:
未命名
时间:
2021-12-31 12:02
标题:
SWOOLE相关知识
<?php
//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9501);
//监听WebSocket连接打开事件
/**
* 客户端想服务器发送信息是调用函数
* $ws websocket 服务器
* $request 客户端信息
* $request->fd 客户端唯一编号
*
* */
$ws->on('open', function ($ws, $request) {
//var_dump($request->fd, $request->get, $request->server);
//$ws->push($request->fd, "hello, welcome\n");
echo "connection open:{$request->fd}\n";
//$ws->push($request->fd, json_encode(['hello','world']));
});
//监听WebSocket消息事件
/**
* $frame 客户端发送的信息
* $frame->fd 客户端的唯一编号
* $frame->data 客户端发送的信息
* */
$ws->on('message', function ($ws, $frame) {
//echo "接收到的信息: {$frame->data}\n";
//$ws->push($frame->fd, "server: {$frame->data}");
//echo "服务器已接收:【".$frame->fd."】";
//$ws->push($frame->fd, json_encode(['hello','world'.$frame->data]));
// 1.客户端发送过来的信息
$content = $frame->data;
echo "服务器接收到信息:".$content;
// 2.讲消息发送个所有客户端
foreach ($ws->connections as $fd){
$ws->push($fd,$content);
}
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
echo "已断开链接:{$fd}";
});
显示数据:
复制代码
来源:
https://www.cnblogs.com/wesky/p/9449647.html
欢迎光临 雅安论坛 (https://www.yaanbbs.net/)
Powered by Discuz! X3.4