I'm trying to send int data via UDP using protobuf. from visual c++ to Java(Android Studio)
proto file:
message rbr
{
required int32 rpm = 1;
required int32 gear = 2;
required int32 speed = 3;
}
C++ sending:
telemetry.set_rpm(1200);
telemetry.set_speed(120);
telemetry.set_gear(4);
telemetry.SerializeToString(&serializedMessage);
memset(message, '\0', BUFLEN);
memcpy(message, serializedMessage.c_str(), serializedMessage.size());
//send the message
if (sendto(s, message, serializedMessage.size(), 0, (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
{
printf("sendto() failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
Java(Android) receive using square wire protobuff library:
socket = new DatagramSocket(8888);
Wire wire = new Wire();
while (true) {
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
s = new String(packet.getData(), 0, packet.getLength());
byte[] bytes = s.getBytes();
rbr newMsg = wire.parseFrom(bytes, rbr.class);
sGear = newMsg.gear.toString();
sRpm = String.valueOf(newMsg.rpm);
sSpeed = newMsg.speed.toString();
tvRpm.post(new Runnable() {
public void run() {
tvRpm.setText(sRpm);
tvGear.setText(sGear);
tvSpeed.setText(sSpeed);
}
});
}
The data is received correctly if the value is below 127, when I send 128 the result is 3104751. But it works fine when I try to receive it in Visual C++ too.
updated code to use SerilizeToArray
int size = telemetry.ByteSize();
char* array = new char[size];
telemetry.SerializeToArray(array, size);
memset(message, '\0', BUFLEN);
memcpy(message, array, size);
but how to receive on java? i try this code but not working.
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
byte[] bytes = packet.getData();
rbr newMsg = wire.parseFrom(bytes, rbr.class);