Sending UDP Datagrams
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 InetAddess("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 e) {
  System.err.println(e);
}
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 e) {
  System.err.println(e);
}
Previous | Next | Top
Last Modified December 17, 1999
Copyright 1997, 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu