swoole学习搭建普通websocket服务
系统:centos7
环境:php7.2+nginx1.16+mysql5.7
php安装swoole扩展
1. git下载swoole扩展
git clone https://github.com/swoole/swoole-src.git
2. 到swoole目录下执行命令 phpize生成configure文件
执行命令
./configure --with-php-config=/usr/bin/php/php-config
注:php-config先查找一下路径,安装方式不同这个配置的路径也不同
3.执行编译
make && make install
4.在php.ini文件中引入模块
增加 extension=swoole.so
5.重新启动php-fpm执行php -m命令就会发现swoole扩展已经安装成功
websocket服务
//创建WebSocket Server对象,监听0.0.0.0:9502端口
$ws = new Swoole\WebSocket\Server('0.0.0.0', 9502);
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
echo $request->fd."\n";
$ws->push($request->fd, "欢迎进入聊天室\n");
});
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
for($i=1;$i<20;$i++){
$ws->push($i,$frame->data);
}
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();

浙公网安备 33010602011771号