我是 TCP 套接字新手,正在尝试使用 Python(服务器)通过 TCP 套接字发送编码图像的大小(整数)。 C# Winforms 应用程序(客户端)用于接收此整数,但接收到的 int 看起来非常随机。例如,如果编码图像是
6570
,则 C# 应用程序会收到 808924470
Python代码(发送者):
## Connection code...
# Send image size
imageSize = len(encodedImage)
socket.send(str(imageSize).encode("utf-8"))
C# 代码(接收器):
// Connection code...
// Receive int
byte[] buffer = new byte[1024]
int bytesReceived = stream.Read(buffer);
int imageSize = BitConverter.ToInt32(buffer, 0);
Python 代码将值作为 UTF 字符串数据发送,即
6570
大部分是字节(十六进制)36-35-37-30。您需要像这样解码它。
最有效的方法是,例如:
var bytes = new byte[] { 0x36, 0x35, 0x37, 0x30 };
if (System.Buffers.Text.Utf8Parser.TryParse(bytes, out int value, out int bytesUsed))
{
Console.WriteLine($"Read {value} from {bytesUsed} bytes");
}
但是,您还需要考虑“框架”; TCP 是流协议,而不是消息协议。