作者:开开2502936987 | 来源:互联网 | 2023-07-12 22:40
server.php
class Chat
{
const HOST = ‘0.0.0.0‘;//ip地址 0.0.0.0代表接受所有ip的访问
const PART = 9501;//端口号
private $server = null;//单例存放websocket_server对象
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, $request)
{
echo $request->fd . ‘连接了‘ . PHP_EOL;//打印到我们终端
$server->push($request->fd,"服务端收到你的连接了");
}
/**
* 接收到信息的回调函数
* @param $server
* @param $frame
*/
public function onMessage($server, $frame)
{
var_dump("收到客户端消息:".$frame->data);
$server->push($frame->fd, "服务端收到你的消息了".$frame->data);
Swoole\Timer::tick(1000, function() use($server,$frame){
$server->push($frame->fd, "当前时间".date("Y-m-d H:i:s"));
});
}
/**
* 断开连接回调函数
* @param $server
* @param $fd
*/
public function onClose($server, $fd)
{
echo $fd . ‘走了‘ . PHP_EOL;//打印到我们终端
}
}
$obj = new Chat();
index.html
模拟Web Socket客户端·向服务端投递Task任务
php server.php
![技术分享图片](https://img6.php1.cn/3cdc5/9cf9/42f/3d98786f04e71b93.jpeg)