udp发送端的代码

private void udpSender(String message, String ipAddress){
        new Thread(()->{
            try {
                 final int PORT = 1234; // 目标端口号
                InetAddress address = InetAddress.getByName(ipAddress);
                // 创建UDP Socket
                DatagramSocket socket = new DatagramSocket();
                byte[] buffer = message.getBytes();
                // 创建要发送的数据包
                for(int i=1;i<=100;i++) {
                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, PORT);
                    // 发送数据包
                    socket.send(packet);

                }
                // 关闭Socket
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();


    }

你可能感兴趣的:(android项目,udp,android,笔记)