<?php
class Ws{
const HOST = '0.0.0.0'; // 监听的IP地址, 0.0.0.0 表示监听所有IP地址
const PROT = '9504';
public $ws = null; // 存放websocket连接资源
// websocket 继承自 http 服务,所以 http 提供的所有 API 和配置项都可以使用,
// websocket 同样支持静态文件的访问。
public $config = [
// 进程数
'worker_num' => 2,
// 开启静态文件请求
'enable_static_handler' => true,
// 配置静态文件根目录
'document_root' => '/www/wwwroot/swoole_gyy/data',
];
public function __construct()
{
// 创建 websocket server对象
$this->ws = new swoole\websocket\server(self::HOST, self::PROT);
// 设置参数
$this->ws->set($this->config);
// 监听websocket连接事件
$this->ws->on('open', [$this, 'onOpen']);
// 监听websocket消息事件
$this->ws->on('message', [$this, 'onMessage']);
// 监听websocket连接关闭事件
$this->ws->on('close', [$this, 'onClose']);
// 启动服务
$this->ws->start();
}
/**
* 监听websocket连接事件
* @param $ws
* @param $request
*/
public function onOpen($ws, $request)
{
echo '已与客户端建立连接 - '. $request->fd. PHP_EOL;
}
/**
* 监听websocket消息事件
* @param $ws
* @param $frame
*/
public function onMessage($ws, $frame)
{
echo '客户端消息:'. $frame->data. PHP_EOL;
// 发送消息给客户端
$ws->push($frame->fd, '这是服务端的消息:'. date('Y-m-d H:i:s'));
}
/**
* 监听websocket连接关闭事件
* @param $ws
* @param $fd
*/
public function onClose($ws, $fd)
{
echo '退出了:'. $fd. PHP_EOL;
}
}
new Ws();
注:WebSocket\Server 继承自 Http\Server,所以 Http\Server 提供的所有 API 和配置项都可以使用。