1

I'm new to both c# and protocoll buffers, and am trying to send a simple message from python to a c# program. So far I haven't got it to work. From python I send the following:

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()

In c# I connect to the socket and receive the Data into a byte array:

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);

My *.proto is a very simple message with two floats:

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

I've tried various things resulting various errors. When I don't trim the byte removing zero bytes i get Google.Protobuf.dll: 'Protocol message contained an invalid tag (zero).'. I then tried only reading the bytes that contain data and get: Google.Protobuf.dll: 'While parsing a protocol message, the input ended unexpectedly in the middle of a field.

I also tried some other protobuf functions e.g. Coord.MergeFrom() etc... but so far no luck. Can anyone let me know what I'm doing wrong?

I could be either with the simple sockets or with the protobuf deserialization.

  • protocol buffers are a binary format but you're doing `SerializeToString()` on the python side? ... nevermind, [`SerializeToString()` : serializes the message and returns it as a string. Note that the bytes are binary, not text; we only use the str type as a convenient container.](https://developers.google.com/protocol-buffers/docs/pythontutorial#parsing-and-serialization). – dbc Dec 14 '19 at 17:36
  • Verify that the full message is received on the c# side. In general you will need to use [message framing](https://stackoverflow.com/q/7257139) to ensure you have received the complete message before trying to deserialize it. – dbc Dec 14 '19 at 17:40
  • @dbc thanks for the comments! I'll look into message framing. I don't think it is the source of the errors, as in my simple example i'm certain i get the whole message my guess the but problem is I get more data in the byte array than i want. – SchillerFalke2 Dec 16 '19 at 08:29

0 Answers0