Joe Bid
Joe Bid

Reputation: 475

Java DatagramPacket, how do I separate it?

So I've currently got a DatagramPacket which gets sent from my client to server. However I'd like to know how I can separate the data into multiple values.

I.E, lets say I want to send two variables, x and y, and then I want to receive them as two variables on the server-side. How would I do this?

int x = 5;
int y = 10;

//Send data to server using a pipe | as a delimiter
byte[] data = Integer.toString(x) + "|" + Integer.toString(y).getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, host, port);

...

//Receive data from client
packet = new DatagramPacket(new byte[PACKETSIZE], PACKETSIZE);

//Receive a packet (blocking)
socket.receive(packet);

int x = packetSeparate(packet, "an integer");
int y = packetSeparate(packet, "an integer");

In other words, on the server side after I've sent the string as a byte array from the client, how would I be able to say: "integer x is the first integer from the byte array known as: packet.getData()".

int x = packet.getData().getAnInteger();
int y = packet.getData().getAnInteger();

Also, would it be efficient say, for a networking game, to send a string as bytes? Or would it be better to convert each individual item into their own bytes and append it to the byte array?

Upvotes: 0

Views: 628

Answers (2)

user207421
user207421

Reputation: 310893

Use DataInputStream:

packet = new DatagramPacket(new byte[PACKETSIZE], PACKETSIZE);

//Receive a packet (blocking)
socket.receive(packet);

DataInputStream din = new DataInputStream(new ByteArrayInputStream(packet.getData(), packet.getOffset(), packet.getLength());

int x = din.readInt();
int y = din.readInt();

Upvotes: 0

Abe
Abe

Reputation: 9031

An integer is 4 bytes long, so read 4 bytes into first integer, read next 4 into next integer. In this way you dont need to use strings to send integers. Just google on how to convert from byte to Integer.

Alternatively you should use a networking library like Netty which has a ByteBuf buffer class which already provides methods like readInt, readLong etc. And while you are at it, there are game servers already written in Netty that might help you out.

Upvotes: 0

Related Questions