集册 Java实例教程 UDP发送包

UDP发送包

欢马劈雪     最近更新时间:2020-01-02 10:19:05

467
UDP发送数据包


import java.net.DatagramPacket;

import java.net.DatagramSocket;
/*
 from nowjava.com - 时  代  Java 
*/

import java.net.InetAddress;

import java.net.SocketException;


public class Main{

    public static void main(String[] argv) throws Exception{

        String xml = "nowjava.com";

        sendPacket(xml);

    }

    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();
      /*
      时代Java公众号 - N o w J a  v a . c o m
      */

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

               } 
展开阅读全文