<?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<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace GatewayWorker\Protocols;
class GatewayProtocol
{
const CMD_ON_CONNECT = 1;
const CMD_ON_MESSAGE = 3;
const CMD_ON_CLOSE = 4;
const CMD_SEND_TO_ONE = 5;
const CMD_SEND_TO_ALL = 6;
const CMD_KICK = 7;
const CMD_DESTROY = 8;
const CMD_UPDATE_SESSION = 9;
const CMD_GET_ALL_CLIENT_SESSIONS = 10;
const CMD_IS_ONLINE = 11;
const CMD_BIND_UID = 12;
const CMD_UNBIND_UID = 13;
const CMD_SEND_TO_UID = 14;
const CMD_GET_CLIENT_ID_BY_UID = 15;
const CMD_JOIN_GROUP = 20;
const CMD_LEAVE_GROUP = 21;
const CMD_SEND_TO_GROUP = 22;
const CMD_GET_CLINET_SESSUONS_BY_GROUP = 23;
const CMD_GET_CLIENT_COUNT_BY_GROUP = 24;
const CMD_SELECT = 25;
const CMD_GET_GROUP_ID_LIST = 26;
const CMD_UNGROUP = 27;
const CMD_WORKER_CONNECT = 200;
const CMD_PING = 201;
const CMD_GATEWAY_CLIENT_CONNECT = 202;
const CMD_GET_SESSION_BY_CLIENT_ID = 203;
const CMD_SET_SESSION = 204;
const CMD_ON_WEBSOCKET_CONNECT = 205;
const FLAG_BODY_IS_SCALAR = 0x01;
const FLAG_NOT_CALL_ENCODE = 0x02;
const HEAD_LEN = 28;
public static $empty = array(
'cmd' => 0,
'local_ip' => 0,
'local_port' => 0,
'client_ip' => 0,
'client_port' => 0,
'connection_id' => 0,
'flag' => 0,
'gateway_port' => 0,
'ext_data' => '',
'body' => '',
);
public static function input($buffer)
{
if (strlen($buffer) < self::HEAD_LEN) {
return 0;
}
$data = unpack("Npack_len", $buffer);
return $data['pack_len'];
}
public static function encode($data)
{
$flag = (int)is_scalar($data['body']);
if (!$flag) {
$data['body'] = serialize($data['body']);
}
$data['flag'] |= $flag;
$ext_len = strlen($data['ext_data']);
$package_len = self::HEAD_LEN + $ext_len + strlen($data['body']);
return pack("NCNnNnNCnN", $package_len,
$data['cmd'], $data['local_ip'],
$data['local_port'], $data['client_ip'],
$data['client_port'], $data['connection_id'],
$data['flag'], $data['gateway_port'],
$ext_len) . $data['ext_data'] . $data['body'];
}
public static function decode($buffer)
{
$data = unpack("Npack_len/Ccmd/Nlocal_ip/nlocal_port/Nclient_ip/nclient_port/Nconnection_id/Cflag/ngateway_port/Next_len",
$buffer);
if ($data['ext_len'] > 0) {
$data['ext_data'] = substr($buffer, self::HEAD_LEN, $data['ext_len']);
if ($data['flag'] & self::FLAG_BODY_IS_SCALAR) {
$data['body'] = substr($buffer, self::HEAD_LEN + $data['ext_len']);
} else {
$data['body'] = unserialize(substr($buffer, self::HEAD_LEN + $data['ext_len']));
}
} else {
$data['ext_data'] = '';
if ($data['flag'] & self::FLAG_BODY_IS_SCALAR) {
$data['body'] = substr($buffer, self::HEAD_LEN);
} else {
$data['body'] = unserialize(substr($buffer, self::HEAD_LEN));
}
}
return $data;
}
}