byte array for transmission using UDP packets
In the lab notes this week I asked for a method of packing and unpacking arbitrary java primatives
into a byte array for transmission using UDP packets.
The ByteArrayOutputStream and the DataOutputStream are your friends in these cases:
// send 4 integers in a UDP packet
ByteArrayOutputStream baos = new ByteArrayOutputStream( MAX_PACKET_SIZE );
DataOutputStream out = new DataOutputStream( baos );
// now send a sequenc of 4 integers ... "2, 4, 6 8"
byte [] data = null;
try {
out.writeInt( 2 );
out.writeInt( 4 );
out.writeInt( 6 );
out.writeInt( 8 );
out.flush();
data = baos.toByteArray();
} catch ( Exception e ) {
usage( "Error formatting data: " + e.getMessage() );
}
// now data (a byte [] ) is ready to send
Similarly, at the receiving end, ue ByteArrayInputStream in conjunction with a DataInputStream:
byte [] data = new byte[ MAX_PACKET_SIZE ];
DatagramSocket s = null;
try {
s = new DatagramSocket( port );
} catch ( Exception e ) {
usage( "Error opening receiving socket: " + e.getMessage() );
}
// loop reading datagrams
while( true ) {
try {
DatagramPacket p = new DatagramPacket( data, data.length );
s.receive(p);
// now decode the data in the byte array
ByteArrayInputStream bais = new ByteArrayInputStream( data );
DataInputStream in = new DataInputStream( bais );
int i1 = in.readInt();
int i2 = in.readInt();
int i3 = in.readInt();
int i4 = in.readInt();
// output result to console
System.out.println( "Received datagram with data "
+i1+" "+i2+" "+i3+" "+i4 );
} catch ( Exception e ) {
usage( "Error reading datagram: " + e.getMessage() );
}
}
We can avoid fiddling with the bits this way.
Full code source