使用php的swoole框架,实现高性能长连接websocket

swoole的官网请见:http://www.swoole.com/
swoole-git:https://github.com/swoole/swoole-src

一.服务器端:

1. 编辑server.php文件内容如下:


$reqs=array(); //保持客户端的长连接在这个数组里
$serv = new swoole_websocket_server("192.168.2.115", 9502);
//如下可以设置多端口监听
//$server = new swoole_websocket_server("0.0.0.0", 9501, SWOOLE_BASE);
//$server->addlistener('0.0.0.0', 9502, SWOOLE_SOCK_UDP);
//$server->set(['worker_num' => 4]);

$serv->on('Open', function($server, $req) {
    global $reqs;
    $reqs[]=$req->fd;
    echo "connection open: ".$req->fd."\n";
    var_dump(count($reqs));//输出长连接数
});

$serv->on('Message', function($server, $frame) {
    global $reqs;
    echo "message: ".$frame->data."\n";
    foreach($reqs as $fd){
            $server->push($fd, $frame->data);
    }
});

$serv->on('Close', function($server, $fd) {
    echo "connection close: ".$fd."\n";
});

$serv->start();

2. 启动上面实现的websocket服务代码

[songaimin@localhost Tests]$/usr/bin/php server.php

客户端-同事打开两个浏览器模拟多client:

3. 在浏览器console里运行:

var wsl= 'ws://192.168.2.115:9502'
ws = new WebSocket(wsl);//新建立一个连接
//如下指定事件处理 
ws.onopen = function(){ws.send('Test!'); };  
ws.onmessage = function(evt){console.log(evt.data);/*ws.close();*/};  
ws.onclose = function(evt){console.log('WebSocketClosed!');};  
ws.onerror = function(evt){console.log('WebSocketError!');}; 

4. 在任意浏览器console里手动执行:

ws.send(888);
//看每个浏览器的内容console输出应该是一样的就实验在成功了
ws.close();//关闭连接

相关推荐文章:
swoole实现的实时聊天室 http://segmentfault.com/a/1190000003057118

你可能感兴趣的:(python,php)