swoole的官网请见:http://www.swoole.com/
swoole-git:https://github.com/swoole/swoole-src
$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();
[songaimin@localhost Tests]$/usr/bin/php server.php
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!');};
ws.send(888);
//看每个浏览器的内容console输出应该是一样的就实验在成功了
ws.close();//关闭连接
相关推荐文章:
swoole实现的实时聊天室 http://segmentfault.com/a/1190000003057118