Java Reference
In-Depth Information
public static void main(String [] args)
{
try
{
String data =
“You have just received a packet of data sent using UDP”;
byte [] buffer = data.getBytes();
DatagramPacket packet = new DatagramPacket(buffer,
buffer.length,
new InetSocketAddress(“localhost”, 5002));
DatagramSocket socket = new DatagramSocket(5003);
System.out.println(“Sending a packet...”);
socket.send(packet);
}catch(IOException e)
{
e.printStackTrace();
}
}
}
The PacketSender program sends a datagram packet to the PacketReceiver
program discussed earlier. Figure 17.8 shows the output of the PacketSender
program.
Figure 17.9 shows the output generated by PacketReceiver when the packet
is delivered. Note that the blank space in Figure 17.9 is caused by the array of
bytes not being entirely filled with the incoming datagram.
Figure 17.8
The PacketSender sends a datagram packet containing a string.
Figure 17.9 The receive() method invoked within PacketReceiver returns after the datagram
packet is delivered.
Search WWH ::




Custom Search