一、下载安装swoole
1.1 使用github安装
git clone https://github.com/swoole/swoole-src
这个下载很慢,我是在网站下载ZIP文件解压后用FTP上传到服务器/usr/local目录下。
1.2 下载好后编译:
cd swoole-src-master //进入文件目录
phpize
./configure
make && sudo make install
1.3 启用扩展
编译安装到系统成功后,需要在 php.ini 中加入一行 extension=swoole.so 来启用 Swoole 扩展。重启PHP
service php-fpm restart
二、使用swoole
查看phpinfo()中有了swoole之后,任一项目中创建serve.php文件。
//创建WebSocket Server对象,监听0.0.0.0:9502端口
$ws = new Swoole\WebSocket\Server('0.0.0.0', 9502);
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
var_dump($request->fd, $request->server);
$ws->push($request->fd, "hello, welcome\n");
});
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
echo "Message: {$frame->data}\n";
$ws->push($frame->fd, "server: {$frame->data}");
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();
运行中便可使用该端口的websocket了。