Read and write with DatagramPacket in Java

Description

The following code shows how to read and write with DatagramPacket.

Example


  /*from   www .  j av a2 s.co m*/


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Main {
  public static void main(String[] args) throws Exception {
    byte[] ary = new byte[128];
    DatagramPacket pack = new DatagramPacket(ary, 128);

    // read
    DatagramSocket sock = new DatagramSocket(1111);
    sock.receive(pack);
    String word = new String(pack.getData());
    System.out.println("From: " + pack.getAddress() + " Port: " + pack.getPort());
    System.out.println(word);
    sock.close();
    // write
    sock = new DatagramSocket();
    pack.setAddress(InetAddress.getByName(args[1]));
    pack.setData(args[2].getBytes());
    pack.setPort(1111);
    sock.send(pack);
    sock.close();

  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Network »




NetworkInterface
URI
URL
HTTP
HTTP Read
IP
Socket
UDP
URL Encode