参考博客,大家可以去看看原文,这里只是根据业务需求做了更改
后端参考
swoole创建多人多房间聊天室一
swoole创建多人多房间聊天室二
swoole创建多人多房间聊天室三
前端参考
微信小程序开发聊天室
搭建环境和域名配置这里就先跳过了,大家可以自行百度
话不多说直接上代码
PHP代码
<?php
define('HOST', '0.0.0.0');
define('PORT', '19501');
define('WORKER_NUM', 10);
define('DISPATCH_MODE', 2);
define('DAEMONIZE', 0);
class WebsocktDemo
{
public $ws = null;
public $redis = null;
public function __construct()
{
$this->ws = new Swoole\WebSocket\Server(HOST, PORT);
$this->redis = $this->redis();
$this->redis->auth("***********");
//$this->ws->on("start", [$this, 'onStart']);
$this->ws->on("open", [$this, 'onOpen']);
$this->ws->on('message',[$this,'onMessage']);
$this->ws->on('close',[$this,'onClose']);
$this->ws->start