脚本宝典收集整理的这篇文章主要介绍了基于swoole实现多人聊天室,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
本文实例为大家分享了swoole创建多人多房间聊天室的具体代码,供大家参考,具体内容如下
基本的cs(client-sercer)结构不变,这里利用的是redis的哈希和set来储存和分组;从而达到了分组,统计,定时推送等功能;最后利用Onclose事件来剔除断开的连接,全部代码如下:(没做前端,就不展示了)
核心的swoole ws.PHP
<PRe class="brush:PHP;">namespace app\common;
require_once 'Predis.php';
require_once 'Task.php';
/**
public function __construct()
{
$this->ws=new \swoole_websocket_server(self::HOST,self::PORT);
$this->ws->set([
//启动task必须要设置其数量
'worker_num' => 4,'task_worker_num' => 2,// 'heartbeat_check_interval' => 5,// 'heartbeat_idle_time' => 10,]);
//监听新端口
$this->server=$this->ws->listen("127.0.0.1",9502,SWOOLE_SOCK_TCP);
//关闭websocket模式
$this->server->set([
'oPEn_websocket_protocol' => false,]);
$this->ws->on("start",[$this,'onStart']);
$this->ws->on('open','onopen']);
$this->server->on("receive",'onReceive']);
$this->ws->on('task','onTask']);
$this->ws->on('finish','onFinish']);
$this->ws->on('message','onmessage']);
$this->ws->on('close','onclose']);
$this->server->on("close",'oncloses']);
$this->ws->start();
}
//监听数据接收事件
public function onReceive($serv,$fd,$From_id,$data)
{
$shuju=json_decode($data,ture);
// print_r($shuju).PHP_EOL;
if (empty($shuju['data'])) {
$this->ws->push(Predis::getInstance()->get('fd'),$data);
}else{
if (empty($shuju['msg'])) {
//执行异步任务
$this->ws->task($shuju);
}else{
$push_arr=Predis::getInstance()->hvals($shuju['data']);
// echo "集群是:".print_r($push_arr);
foreach ($push_arr as $v) {
$this->ws->push($v,$shuju['msg']);
}
}
}
}
/**
/*
监听接收事件的回调
/
public function onmessage($server,$frame)
{
$server->push($frame->fd,"{$frame->data}");
}
/*
监听关闭事件的回调
/
public function onclose($ser,$fd)
{
print_r("你好,我的{$fd}\n");
//退出并删除多余的分组fd
$group=Predis::getInstance()->sMembers('group');
foreach ($group as $v) {
$fangjian=Predis::getInstance()->hgetall($v);
foreach ($fangjian as $k => $vv) {
if ($fd == $vv) {
Predis::getInstance()->hdel($v,$k);
}
}
}
}
public function oncloses($ser,$fd)
{
print_r("这个是client{$fd}\n");
}
/**
}
new Ws();
以上是脚本宝典为你收集整理的基于swoole实现多人聊天室全部内容,希望文章能够帮你解决基于swoole实现多人聊天室所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。