请教使用socket做为客户端和北向接口对接,请教如何打包数据发送。

50785397@qq.com

实时告警采用消息方式,采用socket/tcp协议,OMC为socket的server端,NMS为socket的client端。
5.3.1 消息格式
消息数据由消息头和消息体组成。消息头由9个字节(byte)表示,消息体长度不固定,各类消息不同。消息头的9个字节不能当做字符处理,需要按整型数处理。

上面是文档,下面是我的代码部分,代码是有问题的。

$con->onConnect = function(AsyncTcpConnection $con){

                $messageBody = "reqLoginAlarm;user=xxx;key=xxx;type=xxx";

                $dataArr = explode(";", $messageBody);

                $msgType = $this->msgTypeArr[$dataArr[0]];

                $timeStamp = time();

                $lenOfBody = mb_strlen($messageBody);

                $bytes = new Bytes();

                $startSign = 0xFFFF;

                $startSign = $bytes->shortToBytes ( intval ( $startSign ) );

                $msgType = $bytes->shortToBytes ( intval ( $msgType ) );

                $timeStamp = $bytes->integerToBytes ( intval ( $timeStamp ) );

                $lenOfBody = $bytes->integerToBytes ( intval ( $lenOfBody ) );

                $messageBody =  $bytes->getBytes($messageBody);

                $return_betys = array_merge($startSign, $msgType , $timeStamp , $lenOfBody , $messageBody);

                //$msg = $bytes->toStr ($return_betys);

                // $strLen = strlen($msg);

                // $packet = pack("a{$strLen}", $msg);

                // $pckLen = strlen($packet);

                //Log::channel('workerman')->info($return_betys);

                $con->send($return_betys);

            };
1459 3 0
3个回答

Tinywan
walkor

原代码不变,$con->send($return_betys); 改成 $con->send(implode('', $return_betys)); 试下。发送的数据必须是字符串,不能是数组

walkor

大概是这样

function encode($msgType, $timeStamp, $body)
{
    return "\xFF\xFF".pack('CNn', $msgType, $timeStamp, strlen($body)).$body;
}

$connection->send(encode(1, time(), 'reqLoginAlarm;user=xxx;key=xxx;type=xxx'));
年代过于久远,无法发表回答
🔝