java - How to check the data type exchanged over UDP connection -
is there way determine data type being exchanged client server?
here code example of how think answer should like:
byte[] databook = new byte[1024]; datagrampacket packetr = new datagrampacket(databook, databook.length); ds.receive(packetr); // following psuedo code if (packetr.getdata() off data type string) { // code here } if (packetr.getdata() off data type file) { // diff code here }
packet.getdata() returns array of bytes. interpret it. basically, server needs know method client uses encode data bytes. example (not best option), use java serialization protocol: on client:
bytearrayoutputstream bytes = new bytearrayoutputstream(); objectoutputstream os = new objectoutputstream(bytes); os.writeobject(messagetosend); os.close(); datagrampacket.setdata(bytes.tobytearray()); socket.send(datagrampacket);
then, on server:
byte bytes[] = datagrampacket.getdata(); objectinputstream = new objectinputstream(new bytearrayinputstream(bytes)); serializable messagereceived = is.readobject(); if(messagereceived instanceof string) { handlestring((string) messagereceived); } else { // etc. }
you may find information in tutorial helpful.
Comments
Post a Comment