<?php
/**
* @class WebsocketService //swoole Websocket长连接类
* @author: zhangle
* @date: 2018/6/26
* @return: object
*/
class WebsocketService {
public $server;
public function __construct() {
$this->init();
}
/**
* @function init //swoole Websocket长连接类
* @author: zhangle
* @date: 2018/6/26
*/
private function init(){
try {
//链接swoole_websocket_server服务
$this->server = new swoole_websocket_server("0.0.0.0", 9501);
//捕获客户端请求
$this->server->on('open', function (swoole_websocket_server $server, $request) {
echo $this->messageFormat('open').PHP_EOL;
});
//客户端请求连接成功, 也可以验证心跳
$this->server->on('message', function (swoole_websocket_server $server, $frame) {
$server->push($frame->fd, $this->messageFormat('heartbeat', $frame->fd));
});
//连接关闭
$this->server->on('close', function ($ser, $fd) {
echo $this->messageFormat('close', 'client {$fd} closed\n').PHP_EOL;
});
//推送消息 可获取外部数据
$this->server->on('request', function ($request, $response) {
// 接收http请求从get获取message参数的值,给用户推送
// $this->server->connections 遍历所有websocket连接用户的fd,给所有用户推送
foreach ($this->server->connections as $fd) {
$data = $this->messageFormat('message', $request->get['message']);
$this->server->push($fd, $data);
echo '我要给' . $fd . ' push消息【' . $data . '】' . PHP_EOL;
}
});
$this->server->start();
}catch (Exception $e){
echo $this->messageFormat('Exception', $e->getCode(), $e->getMessage());
}
}
/**
* @function messageFormat //返回数据格式化
* @param string $type 类型 heartbeat【握手成功】, close【关闭】, message【推送内容】
* @param string $data 推送内容 default ''
* @param int $code 状态码 default 200
* @author: zhangle
* @date: 2018/6/26
* @return: string
*/
private function messageFormat($type, $data = '', $code = 200){
$data = array(
'type' => $type,
'code' => $code,
'data' => $data,
);
return json_encode($data);
}
}
//调起代码
new WebsocketService();