java用udp发送数据demo

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u011439839/article/details/83279616

java 使用udp发送数据包时,使用byte数组

public class UdpClientUtil {
    private static final Logger logger = LoggerFactory.getLogger(UdpClientUtil.class);
    public static void sendMessage(Integer operation,String object_name,
                                   Integer port,String address) throws Exception {
        //创建客户端的DatagramSocket对象
        DatagramSocket ds = new DatagramSocket();
        byte[] buf = new byte[257];
        byte[] objectionNameBytes = object_name.getBytes("UTF-8");
        //udp数据格式
        buf[0] = (byte)operation.intValue();
        for(int i = 0 ; i < objectionNameBytes.length;i++){
            buf[i+1] = objectionNameBytes[i];
        }
        logger.info(new String(buf));
        //将字节数组的数据放入数据包
        InetAddress inetAddress = InetAddress.getByName(address);
        DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName(address), port);
        //向客户端传输数据包
        logger.info("===========客户端开始发送消息===========");
        logger.info("operation:"+operation+"object_name:"+object_name);
        logger.info("IP:"+inetAddress.getHostName()+"port:"+port);
        ds.send(dp);
        logger.info("============客户端发送消息完毕=============");
        //关流
        ds.close();
    }

}

 

展开阅读全文

没有更多推荐了,返回首页