使用swoole-WebSocket建立web长链接|聊天室

官方文档地址WebSocket 

1、安装php swoole 拓展:

pecl install swoole  //liunx下,windows不支持

//安装好后提示
Build process completed successfully
Installing '/usr/lib/php/20160303/swoole.so'
install ok: channel://pecl.php.net/swoole-2.0.12
configuration option "php_ini" is not set to php.ini location
You should add "extension=swoole.so" to php.ini

将extension=swoole.so 添加到php.ini 中,
可利用php -i | grep php.ini 找到配置文件地址

重启php-fpm

php -m 查看是否安装成功

 

2、web前端文件 index.html (低版本IE不支持)

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="UTF-8">
    <script type="text/javascript">
        var exampleSocket = new WebSocket("ws://192.168.72.133:9502");
        exampleSocket.onopen = function (event) {
            exampleSocket.send("服务器!我上你啦!");
        };
        exampleSocket.onmessage = function (event) {
            console.log(event.data);
        }
    </script>
</head>
<body>
<input  type="text" id="content">
<button  onclick="exampleSocket.send( document.getElementById('content').value )">发送</button>
</body>
</html>

2、服务端php文件 swoole.php 代码

<?php
$server = new swoole_websocket_server("0.0.0.0", 9502);
$server->on('open', function (swoole_websocket_server $server, $request) {
    echo "建立链接: {$request->fd}\n";
});

$server->on('message', function (swoole_websocket_server $server, $frame) {
    $data = $frame->data;
    echo "发送的消息: {$data}\n";
    foreach($server->connections as $fd) {
        $server->push($fd, $data);
    }
});
$server->on('close', function ($ser, $fd) {
    echo "client {$fd} closed\n";
});
$server->start();

3、服务端执行php文件

 php /home/www/swoole.php  //改为你自己的地址

3、浏览器请求http://(你自己index.html文件的地址)

按F12 查看控制台信息,可建立多个网页