c# - 如何将 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 反序列化。
解决方案
推荐阅读
- batch-file - Windows 批处理文件 - 包含&符号的子字符串变量给出“......不被识别为内部或外部命令......”
- r - 将列名与 r 中的非零列值连接起来
- spring-boot - 如何在 Dockerfile 中更改 war 文件的应用程序属性
- c# - 无法通过 Entity/C# 中的嘲笑来生成新的控制器
- pandas - Python:如何用一系列值替换 Pandas 数据框中的非零值
- python-3.x - 如何用输入数除变量
- javascript - circle.getTotalLength() Internet Explorer 错误
- sql - 在 knex 中创建外部关系时出错 - 表创建竞争条件
- javascript - 如果单击特定按钮,则显示消息
- powershell - PowerShell 从 JSON 对象中提取值,改变