UDP send Packet - Java Network

Java examples for Network:UDP

Description

UDP send Packet

Demo Code


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

public class Main{
    public static void main(String[] argv) throws Exception{
        String xml = "java2s.com";
        sendPacket(xml);//  w  w  w .  ja va 2  s  . com
    }
    private static String ip = IP???;  //??? ip?????????git IP??? 
   

    private static int port = ???;//??? 9999
   

    private static DatagramSocket udpClient;
    public static void sendPacket(String xml) throws Exception{
      System.out.println("---UDP send packet xml:"+xml);
      byte[] sendBuf = xml.getBytes();
      DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length,
            InetAddress.getByName(ip), port);
      UDPClientUtil.getUDPClient().send(sendPacket);
   }
    public static DatagramSocket getUDPClient(){
      if(udpClient == null){
         synchronized (Object.class) {
            if(udpClient == null){
               try {
                  udpClient = new DatagramSocket();
               } catch (SocketException e) {
                  // TODO Auto-generated catch block
                  System.out.println("------DatagramSocket failed------");
                  e.printStackTrace();
               }
            }
         }
      }
      return udpClient;
   }
}

Related Tutorials