Read and write with DatagramPacket : DatagramSocket « Network Protocol « Java






Read and write with DatagramPacket

 

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();

  }
}

   
  








Related examples in the same category

1.Use DatagramSocket to send out and receive DatagramPacket
2.DatagramSocket sends out DatagramPacket
3.DatagramSocket receives DatagramPacket
4.Datagram Sender
5.Sending a Datagram
6.Receiving a Datagram
7.Joining a Multicast Group
8.Receiving from a Multicast Group
9.Sending to a Multicast Group
10.Receive DatagramPacket
11.Send a Datagram
12.User Datagram Protocol Programming
13.Send back the response in a DatagramPacket