You can create "protocole" JSON-based like this:
{"items":[ {"type":'string", "value":"test"}, {"type":"int", "value":3}]}
and use https://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_Encode_a_JSON_object to encode it.
質問
I am trying to create a client in java which sends data to a python server using UDP,but i am having trouble sending data. Every example which i have seen or read so far is something like this:
byte[] buf = new byte[256];
InetAddress address = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(buf, buf.length, ip,port);
System.out.println("Sending...");
socket.send(packet);
What i can't figure out is how can i send my data which can be of type int or char or string or even an array?? I mean how do I change these to byte,put it in buf and send them. Can it then be simply be decoded on python client like this:
data,addr = self.sock.recvfrom(1024)
data = data.decode()
EDIT:
I have figured out how to convert strings to byte, by doing:
buf = "hello".getBytes();
But still no clue on integers and arrays..
解決
You can create "protocole" JSON-based like this:
{"items":[ {"type":'string", "value":"test"}, {"type":"int", "value":3}]}
and use https://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_Encode_a_JSON_object to encode it.