本文主要是介绍java用udp发送数据demo,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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();}}
这篇关于java用udp发送数据demo的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!