Global Positioning System Reference
In-Depth Information
public int ID = -1, numCards = 0, wolfCries = 0;
public String name;
// 1. regular construction in the java environment:
public PlayerRecord(int ID, String name, int numCards) {
this.ID = ID; this.name = name;
this.numCards = numCards; this.wolfCries = 0;
}
// 2. sender disassembles object to a byte array:
public byte[] getBytes()
{
byte[] numbers
= { (byte)ID, (byte)numCards, (byte)wolfCries };
byte[] nameBytes = name.getBytes();
byte[] answer
= new byte[numbers.length + nameBytes.length];
System.arraycopy
(numbers, 0, answer, 0, numbers.length);
System.arraycopy
(nameBytes, 0, answer, numbers.length,
nameBytes.length);
return answer;
}
// 3. receiver reconstructs new object from a byte array:
public PlayerRecord(byte[] b) {
//
single byte fields
this.ID = (int)b[0]; this.numCards = (int)b[1];
this.wolfCries = (int)b[2];
//
bytes to a String field
byte[] nameBytes = new byte[b.length-3];
System.arraycopy
(b, 3, nameBytes, 0, nameBytes.length);
this.name = new String(nameBytes);
}
}
The listing points out the fine print of UDP communication: server and
client have to agree precisely how to disassemble and reassemble the trans-
mitted information and to what. In other words, they have to come up
with their own protocol. With the built-in protocol of RMI and serializing
objects, the programmer only has to know what to send and receive. Note
that the PlayerRecord is not tagged to be Serializable .
The byte array is packed into a DatagramPacket for the actual broadcast-
ing:
class SocketGate
{
...
void sendPlayerStatusMessage(PlayerRecord p)
{ sendBytes(p.getBytes(), playerListeningGroup); }
 
Search WWH ::




Custom Search