CentOS 安装 Swoole 扩展

根据Swoole文档,直接install

pecl install swoole

但是报错,需要root权限。

sudo su
pecl install swoole

但是提了一个warning

WARNING: channel "pecl.php.net" has updated its protocols, use "pecl channel-update pecl.php.net" to update

于是,直接顺手update一下吧

pecl channel-update pecl.php.net

查找下php.ini的位置

php -i |grep php.ini

然后在php.ini中增加

extension=swoole.so

重启下php

systemctl restart php

查看下是否已经成功加载了swoole

php -m | grep swoole

Ps:到此swoole扩展就安装完成了,因为我的代码运行成功,所以后面的步骤我就没走下去了,就留给童鞋们自己试咯~


Test

新建一个文件,我命名为SwooleServer.php文件
代码如下:

<?php
//创建websocket服务器对象,监听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->get, $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();
?>

然后创建一个html文件,用于模拟访问的Client:

<!DOCTYPE html>  
<meta charset="utf-8" />  
<title>WebSocket Test</title>  
<script language="javascript"type="text/javascript">  
    var wsServer = 'ws://192.168.10.10:9502';
    var websocket = new WebSocket(wsServer);
    websocket.onopen = function (evt) {
        console.log("Connected to WebSocket server.");
    };
    
    websocket.onclose = function (evt) {
        console.log("Disconnected");
    };
    
    websocket.onmessage = function (evt) {
        console.log('Retrieved data from server: ' + evt.data);
    };
    
    websocket.onerror = function (evt, e) {
        console.log('Error occured: ' + evt.data);
    };
</script>  
</html>

启动服务:

php SwooleServer.php

访问该Html,在控制台中可以看到

Connected to WebSocket server.
Retrieved data from server: hello, welcome



技苑
请先登录后发表评论
  • 最新评论
  • 总共0条评论
  • © 2016-2024 技苑 | PHP是最好的语言 版权所有 ICP证:鄂ICP备15021999号-4
  • 联系邮箱:master@pengxb.com