首页 > 解决方案 > 如何将 c# 中的 protobuf 消息反序列化,通过套接字读入字节数组?

问题描述

我是 c# 和 protocoll 缓冲区的新手,我正在尝试从 python 向 ac# 程序发送一条简单的消息。到目前为止,我还没有让它工作。从 python 我发送以下内容:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverAddress = ('localhost', 2211)
sock.bind(serverAddress)
sock.listen(1)
connection, clientAddress = sock.accept()

message = protos.testproto_pb2.Coordinate()
message.Row = 12.3
message.Col = 12.4
connection.sendall(message.SerializeToString())

connection.close()

在 c# 中,我连接到套接字并将数据接收到一个字节数组中:

Byte[] bytesReceived;
var server = (ip:"127.0.0.1", port: 2211);

IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(server.ip), server.port);
Socket mySocket = 
    new Socket(serverEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

Coordinate Coord = new Coordinate{Row = 0, Col = 0};

mySocket.Connect(serverEndPoint);

bytes = mySocket.Receive(bytesReceived, bytesReceived.Length, 0);

Coord = Coordinate.Parser.ParseFrom(bytesReceived);

我的 *.proto 是一个非常简单的消息,带有两个浮点数:

message Coordinate{
    //coordinates
    float Row = 1;
    float Col = 2;
}

我尝试了各种导致各种错误的事情。当我不修剪删除零字节的字节时,我得到Google.Protobuf.dll: 'Protocol message contained an invalid tag (zero).'. 然后我尝试只读取包含数据的字节并得到:Google.Protobuf.dll: 'While parsing a protocol message, the input ended unexpectedly in the middle of a field.

我还尝试了其他一些 protobuf 函数,例如Coord.MergeFrom()等……但到目前为止还没有运气。谁能让我知道我做错了什么?

我可以使用简单的套接字或使用 protobuf 反序列化。

标签: c#pythonsocketsprotocol-buffersproto

解决方案


推荐阅读