Events.php 消息处理
<?php
/**
* This file is part of workerman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<[email protected]>
* @copyright walkor<[email protected]>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* 用于检测业务代码死循环或者长时间阻塞等问题
* 如果发现业务卡死,可以将下面declare打开(去掉//注释),并执行php start.php reload
* 然后观察一段时间workerman.log看是否有process_timeout异常
*/
//declare(ticks=1);
/**
* 聊天主逻辑
* 主要是处理 onMessage onClose
*/
use \GatewayWorker\Lib\Gateway;
use \Workerman\MySQL\Connection;
require_once __DIR__.'/config/db.php';
date_default_timezone_set("Asia/Shanghai");
class Events
{
protected static $db = '';
protected static $chat;
protected static $redisUsers;
/**
* @todo 自动回复消息默认配置
* @var string[]
*/
protected static $sysRobot = [
'client_id' => 'longer7f00000108fc00000001',
'client_name' => 'systemRobot',
'client_img' => 'https://cdn.pixabay.com/photo/2016/12/13/21/20/alien-1905155_960_720.png',
'content' => '欢迎您的到来!'
];
/**
* 有消息时
* @param $from_client_id //workerman 生成的client_id
* @param $message
* @return bool
* @throws \Exception|boolean
*/
public static function onMessage($from_client_id, $message)
{
// 客户端传递的是json数据
$message_data = json_decode($message, true);
if (!$message_data) {
return false;
}
self::$chat = new Chat();
// 获取在线用户
self::$redisUsers = self::$chat->sMembers(REDIS_KEY);
$clients_list = self::getUserLists(self::$redisUsers);
// 根据类型执行不同的业务
switch ($message_data['type']) {
// 客户端回应服务端的心跳
case 'pong':
echo '';
break;
// 客户端登录 message格式: {type:login, name:xx, room_id:1} ,添加到客户端,广播给所有客户端xx进入聊天室
case 'login':
// 判断是否有房间号
if (!isset($message_data['room_id'])) {
throw new \Exception("\$message_data['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:$message");
}
// 把房间号昵称放到session中
$room_id = $message_data['room_id'];
$from_client_name = htmlspecialchars($message_data['client_name']);
$_SESSION['room_id'] = $room_id;
$_SESSION['client_name'] = $from_client_name;
$_SESSION['uid'] = $message_data['uid'];
//添加用户到redis
if (!self::$chat->sIsMember(REDIS_KEY, $message_data['uid'])) {
self::$chat->sAdd(REDIS_KEY, $message_data['uid']);
}
self::$redisUsers = self::$chat->sMembers(REDIS_KEY);
$clients_list = self::getUserLists(self::$redisUsers);
// 转播给当前房间的所有客户端,xx进入聊天室 message {type:login, client_id:xx, name:xx}
$new_message = array(
'type'=>'login',
'from_client_id'=>$message_data['from_client_id'],
'from_client_name'=>htmlspecialchars($from_client_name),
'to_client_id' => 'all',
'to_client_name' => 'all',
'time'=>date('Y-m-d H:i:s'),
'client_img' => $message_data['client_img'],
'client_list' => $clients_list,
'room_id' =>$room_id,