Earlier I have been sending strings over TCP and then used ‘substring’ to locate the exact data I’m interested in.
I was just wondering if there is a better way, i.e. byte arrays or something like that.
The data I’ll mostly be sending is coordinates. UDP would be very nice to. Thanks!
ByteBuffers work quite nicely for this, especially as you can .slice() the resulting input into packet sized chunks to hand off for decoding, or view as float or int buffers to extract these types.
This works great for me:
CLIENT SIDE
ByteBuffer buffer = ByteBuffer.allocate(256);
byte[] buf = buffer.array();
InetAddress address = InetAddress.getByName("localhost");
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
//waiting for server to return packet
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
byte[] received = packet.getData();
buffer = ByteBuffer.wrap(received);
System.out.println(buffer.getDouble());
System.out.println(buffer.getDouble());
SERVER SIDE
ByteBuffer buffer = ByteBuffer.allocate(256);
byte[] buf = buffer.array();
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
buffer = ByteBuffer.wrap(packet.getData());
buffer.putDouble(8.0D);
buffer.putDouble(32.0D);
buf = buffer.array();
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
Thanks!
Maybe you should try the HeadQuarter system. One part of HQ is a slim API around ByteBuffers/NIO networking that makes it easy to use. Also covers creation of connections, common notifactions and also offers some services that might be useful.
Start here: http://www.flyingguns.com and contact me when questions arise.
You may use DataInputStream to read and DataOutputStream to write
- this will enable you to send/receive all type of informations : byte,int,double etc… and String or any other serializable object.
Bruno