Mega Code Archive

 
Categories / Java Tutorial / Network
 

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