Java Reference
In-Depth Information
import java.net.*;
import java.io.*;
public class PacketReceiver
{
public static void main(String [] args)
{
try
{
byte [] buffer = new byte[1024];
DatagramPacket packet =
new DatagramPacket(buffer, buffer.length);
DatagramSocket socket = new DatagramSocket(5002);
System.out.println(“Waiting for a packet...”);
socket.receive(packet);
System.out.println(“Just received packet from “
+ packet.getSocketAddress());
buffer = packet.getData();
System.out.println(new String(buffer));
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Sending a Datagram Packet
To receive a datagram packet, the following steps are performed:
1.
Create an array of bytes large enough to hold the data of the packet to
be sent, and fill the array with the data.
2.
Create a new DatagramPacket object that contains the array of bytes, as
well as the server name and port number of the recipient.
3.
A DatagramSocket is instantiated, and it is specified which port (and spe-
cific localhost address, if necessary) on the localhost the socket will bind to.
4.
The send() method of the DatagramSocket class is invoked, passing in
the DatagramPacket object.
The following PacketSender class sends a packet containing a string. Notice
that the String object is converted to an array of bytes using the getBytes()
method of the String class.
import java.net.*;
import java.io.*;
public class PacketSender
{
Search WWH ::




Custom Search