环境配置
LNMP环境 安装swoole扩展
服务端代码
使用swoole提供的websocket的服务
<?php
class Chat
{
const HOST = '0.0.0.0';//ip地址 0.0.0.0代表接受所有ip的访问
const PART = 9502;//端口号
private $server = null;//单例存放websocket_server对象
private $connectList = [];//客户端的id集合
//初始化
public function __construct()
{
//实例化swoole_websocket_server并存储在我们Chat类中的属性上,达到单例的设计
$this->server = new swoole_websocket_server(self::HOST, self::PART);
//监听连接事件
$this->server->on('open', [$this, 'onOpen']);
//监听接收消息事件
$this->server->on('message', [$this, 'onMessage']);
//监听关闭事件
$this->server->on('close', [$this, 'onClose']);
//开启服务
$this->server->start();
}
/**
* 连接成功回调函数
* @param $server
* @param $request
*/
public function onOpen($server, $req)