Вопрос

Hi I have a very simple Java server and two clients. One client is Java based and other is python based. When I send any string from Java client to java server or vice versa it works fine. When I send any string from Java to python it also works fine. But when I send a string from python which is generated by python json lib using json.dumps, I receive a buffer in Java containing desired data and null bytes. There is no indication of start or end of string. How do i convert it back to String of same length. Currently the string has a lot of null bytes after JSON data is finished thats why I wont be able to parse that string correctly.

Receive code for Java is like this.

byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
CtrlChannel.getSocket().receive(receivePacket);
strData = new String(receivePacket.getData());
System.out.println("FROM PYTHON:" + strData);

Sender code of python is like this.

...
...
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
data = {}
data["type1"] = "type1"
data["type2"] = "type2"
data["type3"] = "type3"
data["type4"] = "type4"

data_string = json.dumps(data)
sock.sendto(data_string, (addr[0], 36963))
...
...

I am new to Java so there may be some silly mistake I am doing. PLease help.

Это было полезно?

Решение

In your java code you use a 1024 byte buffer to recieve udp packets, which will only be filled partially if you don't receive enough bytes. receivePacket.getData() simply returns this buffer.

When you then convert it to a String, of course the remaining bytes will be filled with whatever was in the buffer before (in this case zero bytes, but could als be filled with content if you used it as receiving buffer before).

The correct way to get the received data would be to use the getLength() and getOffset() methods of DatagramPacket:

strData = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top