swoole使用websocket及tcp实现一个h5聊天室效果代码
代码语言:phpcli
所属分类:通讯
代码描述:swoole使用websocket及tcp实现一个h5聊天室效果代码
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<?php
class Server
{
private $serv;
public function __construct() {
$this->serv = new swoole_websocket_server("0.0.0.0", 9501);
$this->serv->set([
'worker_num' => 2, //开启2个worker进程
'max_request' => 4, //每个worker进程 max_request设置为4次
'task_worker_num' => 4, //开启4个task进程
'dispatch_mode' => 4, //数据包分发策略 - IP分配
'daemonize' => false, //守护进程(true/false)
]);
//监听WebSocket连接打开事件
$this->serv->on('Open', function ($ws, $request) {
$ws->push($request->fd, "hello, welcome\n");
});
//监听WebSocket消息事件
$this->serv->on('Message', function ($ws, $frame) {
$data = $frame->data;
$res['data'] = $data;
foreach ($ws->connections as $client) {
if ($frame->fd == $client) {
$res['style'] = 'bubble me';
} else {
$res['style'] = 'bubble you';
}
@$ws->push($client, json_encode($res, 256));
}
});
//监听WebSocket连接关闭事件
$this->serv->on('Close',
function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$this->serv->on('Start',
[$this,
'onStart']);
//$this->serv->on('Open', [$this, 'onOpen']);
// $this->serv->on("Message", [$this, 'onMessage']);
$this->serv->on("Request",
[$this,
'onRequest']);
// $this->serv->on("Close", [$this, 'onClo.........完整代码请登录后点击上方下载按钮下载查看















网友评论0