首页>代码>java网络编程实现udp数据发送与接收的简单实例>/UdpTools/src/com/jxkj/udp/client/UdpClient.java
package com.jxkj.udp.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Arrays;

import org.apache.log4j.Logger;

import com.jxkj.util.Util;
/**
 * 发送UDP数据
 * @author sourcezero
 *
 */
public class UdpClient {
    private static Logger logger = Logger.getLogger(UdpClient.class);
    private static String ip="127.0.0.1";//发向地址
    private static int port=9999;//发向端口
    private static int sleep = 2;//休眠时间 
    
    
    public static void main(String[] args)  {
        DatagramSocket client = null;
        byte[] sendBuf;
        if(args!=null&&args.length>0){
            port = Integer.valueOf(args[0]);
        }
        try {
            System.out.println("启动UDP发送程序:发送端口"+port);
            StringBuffer contents = new StringBuffer();
            contents.append("测试UDP中文广播");
            contents.append("ok");
            client = new DatagramSocket(50000);
            byte[] headbt = hexStringToByte(getUdpHead(contents.length()*4,1,1,1));
            byte[] bodybt =  Util.string2Hex(contents.toString(), 4).getBytes();
            sendBuf = addBytes(headbt,bodybt);
            
            InetAddress addr = InetAddress.getByName(ip);
            DatagramPacket sendPacket 
                = new DatagramPacket(sendBuf ,sendBuf.length , addr , port);
            while(true){
                client.send(sendPacket);
                System.out.println(Arrays.toString(sendPacket.getData()));
                try {
                    Thread.sleep(sleep*1000);
                } catch (InterruptedException e) {
                    logger.error(e);
                }
            }
        } catch (IOException e) {
            logger.error(e);
        } finally{
            if(client!=null){
                client.close();
            }
        }
    }
    
    /**
     * 
     * @param total   报文长度
     * @param count   数据个数
     * @param start   起始地址
     * @param tbType  对应表类型
     * @return
     */
    public static String getUdpHead(int total,int count,int start,int tbType){
        StringBuffer sb = new StringBuffer();
        String hexTotal = addZeroForNum(Integer.toHexString(total).toUpperCase(),4);
        String hexCount = addZeroForNum(Integer.toHexString(count).toUpperCase(),4);
        String hexStart = addZeroForNum(Integer.toHexString(start).toUpperCase(),4);
        String hexTbType = addZeroForNum(Integer.toHexString(tbType).toUpperCase(),4);
        //启动字符          发送站地址           报文长度
        sb.append("68").append("01").append(hexTotal);
         
        //数据类型        数据个数1个     起始地址1
        sb.append("10").append(hexCount).append(hexStart);
        //对应表类型
        sb.append(hexTbType);
        return sb.toString();
    }
     

    public static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    private static int toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }
    
    
    public static byte[] addBytes(byte[] data1, byte[] data2) {  
        byte[] data3 = new byte[data1.length + data2.length];  
        System.arraycopy(data1, 0, data3, 0, data1.length);  
        System.arraycopy(data2, 0, data3, data1.length, data2.length);  
        return data3;  
    } 
    /**
     * 左补0
     * 
     * @param str
     * @param strLength
     * @return
     */
    public static String addZeroForNum(String str, int strLength) {
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append("0").append(str);// 左补0
                // sb.append(str).append("0");//右补0
                str = sb.toString();
                strLen = str.length();
            }
        }
        return str;
    }
}
最近下载更多
zhendong  LV7 2022年3月6日
shan454  LV3 2022年1月24日
ITfans  LV19 2020年12月31日
liuxie  LV12 2020年12月14日
KKnight  LV1 2020年6月20日
fanxiaolin84  LV10 2019年12月26日
fzjlyq  LV1 2019年12月17日
樊樊樊樊樊樊阵雨  LV18 2019年9月10日
ly3812  LV17 2019年4月16日
1847731288  LV13 2019年4月15日
最近浏览更多
钱小小  LV3 2023年7月15日
2543317781 2022年11月26日
暂无贡献等级
陨石承影  LV1 2022年10月21日
adimgaoshou  LV10 2022年9月6日
twy525252 2022年5月31日
暂无贡献等级
zhendong  LV7 2022年3月6日
shan454  LV3 2022年1月24日
dongzhan  LV12 2021年12月15日
baotong  LV7 2021年8月2日
tianli3000  LV8 2021年7月22日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友