在上一个例子中,实现了多房间的多人聊天,这次这个聊天室有所改变,需要做到类似微信或QQ那样(app,pc同时使用),多个端口登入,保证数据的同时传递,考虑了很久,最好的办法就是在之前代码的基础上,再加一层redis的关系,结构脑图如下:
简单点说也就是group->房间room_id->uid->fd,因为全是键值对的关系,所以我这里为了好区分全部用的是redis集合;
代码如下:
<?php
namespace app\common;
require_once 'Predis.php';
require_once 'Task.php';
/**
* socket面向对象的编译
*/
class Http
{
CONST HOST='0.0.0.0';
CONST PORT='9501';
public $ws=null;
public $http_server=null;
private $key='paiv3@$))(';
private $prefix='paiv3_';
public function __construct()
{
$this->ws=new \swoole_websocket_server(self::HOST,self::PORT);
$this->ws->set([
//心跳检测
// 'heartbeat_check_interval' => 5,
// 'heartbeat_idle_time' => 10,
]);
//监听新端口
$this->http_server=$this->ws->listen("0.0.0.0", 9502, SWOOLE_SOCK_TCP);
//开启http模式
$this->http_server->set([
'open_http_protocol' => true,
]);
$this->ws->on("start", [$this, 'onStart']);
$this->http_server->on("request", [$this, 'onRequest']);
$this->ws->on('message',[$this,'