To send data to a particular server, you first must convert the
data into byte array. Next you pass this byte array, the length of
the data in the array (most of the time this will be the length of
the array) and the InetAddress
and port to which you
wish to send it into the DatagramPacket()
constructor.
For example,
try {
InetAddress metalab = new InetAddress("metalab.unc.edu");
int chargen = 19;
String s = "My second UDP Packet";
byte[] b = s.getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length, metalab, chargen);
}
catch (UnknownHostException ex) {
System.err.println(ex);
}
Next you create a DatagramSocket
object and pass the
packet to its send() method: For example,
try {
DatagramSocket sender = new DatagramSocket();
sender.send(dp);
}
catch (IOException ex) {
System.err.println(ex);
}