发送带有前导长度值的套接字数据 [英] Sending sockets data with a leading length value

查看:112
本文介绍了发送带有前导长度值的套接字数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 通常,对于二进制协议,每封邮件的前4个字节必须是代表长度的整数(邮件).

Usually, for binary protocols, the first 4 bytes of every message must be an integer which represents the length (how many bytes) of the message.

在C#中,我为每条消息加上一个整数,该整数表示消息的长度,如下所示:

In C# I prefix every message with an integer that tells the length of the message as follow:

byte[] msgBytes = UTF8Encoding.UTF8.GetBytes("A JSON msg");            
byte[] prefixBytes = BitConverter.GetBytes(msgBytes.Length);
byte[] msgToSend = new byte[prefixBytes.Length + msgBytes.Length];
Buffer.BlockCopy(prefixBytes, 0, msgToSend, 0, prefixBytes.Length);
Buffer.BlockCopy(msgBytes, 0, msgToSend, prefixBytes.Length, msgBytes.Length);

据我了解,在PHP中,函数 socket_send 只接受字符串.那么,如何在PHP 5.x中执行相同的前缀?

As I understand, in PHP the function socket_send only accept strings. So, how can I do the same prefixing in PHP 5.x?

更新:我发布了跟随问题:从网络套接字接收时如何处理此类带前缀的数据.

Update: I posted a follow-up question on how to process such prefixed data when received from a network socket.

推荐答案

在PHP中,字符串是二进制的.

In PHP strings are binary.

因此,您需要将整数长度值编码为4个字符(4个八位位组; 32位)字符串的 n un 带符号整数的二进制表示形式.参见 pack :

So you need to encode the integer length value as the binary representation of an unsigned integer as a 4-char (4 Octets; 32 bits) string. See pack:

# choose the right format according to your byte-order needs:

l   signed long (always 32 bit, machine byte order)
L   unsigned long (always 32 bit, machine byte order)
N   unsigned long (always 32 bit, big endian byte order)
V   unsigned long (always 32 bit, little endian byte order)

$string = pack('l', $length);

这篇关于发送带有前导长度值的套接字数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆