Sending UDP to a Server
- Convert the data into byte array.
- Pass this byte array, the length of the data array,the
InetAddress and port to target DatagramPacket() constructor.
- Next create a DatagramSocket and pass the packet to its send()
method
- Example:
try {
InetAddress intaddr = new InetAddess("intaddr.ABC.com");
int n1 = 40;
String str1 = "My second UDP Packet"
byte[] bt1 = str1.getBytes();
DatagramPacket dp = new DatagramPacket(bt1, bt1.length, intaddr,
n1);
}
catch (UnknownHostException e) {
System.err.println(e);
}
|
Receiving UDP datagram
- Construct a in bound DatagramSocket object on the port
- Pass an empty DatagramPacket object to the DatagramSocket's
receive() method.
- The calling thread will lockup until a datagram is received.
- With getPort() and and getAddress() tender the the source of
packed came from,
- Use getData() to retrieve the data, and getLength() to
bytes-size were in the data.
- When received packet was too long for the buffer, the packet
would truncated to the length of the buffer.
- The Length of the packet is reset after receiving complete
packet
An Example:
try {
byte buffer = new byte[45000];
DatagramPacket inDP = new DatagramPacket(buffer, buffer.length);
DatagramSocket inDS = new DatagramSocket(5678);
inDS.receive(inDP);
byte[] data = inDP.getData();
String str1 = new String(data, 0, data.getLength());
System.out.println("getPort" + inDP.getPort() + " address "
+ inDP.getAddress() + " notes:");
System.out.println(str1);
}
catch (IOException e) {
System.err.println(e);
}
|