89 lines
3.0 KiB
PHP
89 lines
3.0 KiB
PHP
|
<?php
|
|||
|
class Chat{
|
|||
|
private $server = null;//单例存放websocket_server对象
|
|||
|
private $roles = [
|
|||
|
'郭靖','杨过','洪七公','尹志平','赵志敬','丘处机','欧阳锋','一灯大师','黄药师'
|
|||
|
];
|
|||
|
public function __construct(){
|
|||
|
$info=file_get_contents('./web/cacheSet.log');
|
|||
|
$port=json_decode($info,true)['swoole'];
|
|||
|
|
|||
|
//$redisPassWd=json_decode($info,true)['redis'];
|
|||
|
$ssl_certificate=json_decode($info,true)['ssl_certificate'];
|
|||
|
$ssl_certificate_key=json_decode($info,true)['ssl_certificate_key'];
|
|||
|
//实例化swoole_websocket_server并存储在我们Chat类中的属性上,达到单例的设计
|
|||
|
$this->server =new swoole_websocket_server("0.0.0.0","9527",SWOOLE_BASE, SWOOLE_SOCK_TCP | SWOOLE_SSL );
|
|||
|
$this->server->on('WorkerStart',[$this,'onWokerStart']);
|
|||
|
//监听连接事件
|
|||
|
$this->server->on('open', [$this, 'onOpen']);
|
|||
|
//监听接收消息事件
|
|||
|
$this->server->on('message', [$this, 'onMessage']);
|
|||
|
//监听关闭事件
|
|||
|
$this->server->on('close', [$this, 'onClose']);
|
|||
|
//设置允许访问静态文件
|
|||
|
$this->server->set([
|
|||
|
'document_root' => '/www/chat1',//这里传入静态文件的目录
|
|||
|
'enable_static_handler' => true,//允许访问静态文件
|
|||
|
'ssl_cert_file'=>$ssl_certificate,//https证书位置
|
|||
|
'ssl_key_file'=>$ssl_certificate_key,//https证书位置
|
|||
|
'daemonize'=>0
|
|||
|
]);
|
|||
|
|
|||
|
|
|||
|
//开启服务
|
|||
|
$this->server->start();
|
|||
|
}
|
|||
|
public function onWokerStart($server,$woker_id){
|
|||
|
if($woker_id==0){
|
|||
|
echo 'id是'.$woker_id;
|
|||
|
}
|
|||
|
}
|
|||
|
/**
|
|||
|
* 连接成功回调函数
|
|||
|
* @param $server
|
|||
|
* @param $request
|
|||
|
*/
|
|||
|
public function onOpen($server, $request)
|
|||
|
{
|
|||
|
echo $request->fd . '连接了' . PHP_EOL;//打印到我们终端
|
|||
|
$server->push($request->fd,json_encode(['no' => $request->fd, 'msg' =>'']));
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* 接收到信息的回调函数
|
|||
|
* @param $server
|
|||
|
* @param $frame
|
|||
|
*/
|
|||
|
public function onMessage($server, $frame)
|
|||
|
{
|
|||
|
$role = $this->getRole($frame->fd);
|
|||
|
echo $role. '来了,说:' . $frame->data . PHP_EOL;//打印到我们终端
|
|||
|
foreach ($server->connections as $fd) {//遍历TCP连接迭代器,拿到每个在线的客户端id
|
|||
|
//将客户端发来的消息,推送给所有用户,也可以叫广播给所有在线客户端
|
|||
|
$msg = $frame->data;
|
|||
|
$server->push($fd, json_encode(['no' => $frame->fd,'role'=>$role, 'msg' => $msg]));
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
public function getRole($fd)
|
|||
|
{
|
|||
|
$roles = count($this->roles);
|
|||
|
$role = ($fd < $roles) ? $this->roles[$fd] : $this->roles[$fd%$roles];
|
|||
|
var_dump($role);
|
|||
|
return $role;
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* 断开连接回调函数
|
|||
|
* @param $server
|
|||
|
* @param $fd
|
|||
|
*/
|
|||
|
public function onClose($server, $fd)
|
|||
|
{
|
|||
|
echo $fd . '走了' . PHP_EOL;//打印到我们终端
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
$obj = new Chat();
|