C# 中有一个服务器从客户端读取消息,如下所示:
private string ReadMessageWithPrefixLength()
{
var length = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(ReadBytes(sizeof(int)), 0));
return Encoding.UTF8.GetString(ReadBytes(length));
}
private byte[] ReadBytes(int size)
{
var buffer = new byte[size];
int alreadyReadCount = 0;
while (size - alreadyReadCount > 0)
{
var read = stream.Read(buffer, alreadyReadCount, size - alreadyReadCount);
if (read == 0)
throw new EndOfStreamException();
alreadyReadCount += read;
}
return buffer;
}
Python 中有一个客户端必须首先发送消息的长度,然后发送消息本身:
sendMessage = "message"
socket.send(len(sendMessage).to_bytes(2, "big"))
socket.send(sendMessage.encode())
每次我尝试读取服务器上的消息长度时,我都会得到一个负值(或相反太大)。我究竟做错了什么?