UDP简单通信例子

/*
 *通过Udp将文字发送出去
 * 提供数据,封装数据包
 * socket发送
 * 关闭资源
 */

class UdpSendDemo {
    public static void main(String[] args) throws IOException {
        //创建udp服务
        DatagramSocket ds = new DatagramSocket();
        //确定数据 封装为数据包
        byte[] data = "我是发送端".getBytes();
        DatagramPacket dp = new DatagramPacket(data,data.length, InetAddress.getByName("127.0.0.1"),10000);
        //发送
        ds.send(dp);
        //关闭
        ds.close();
    }
}
/**
 * 接收udp传过来的数据
 * 定义udpsocket服务 监听一个端口
 * 通过socket服务的recive方法将收到的数据存入以定义好的数据包中
 * 打出控制台
 * 关闭资源
 */
class UdpReciveDemo {
    public static void main(String[] args) throws IOException {
        //创建udp socket建立端点
        DatagramSocket ds = new DatagramSocket(10000 );
        //定义数据包用于存储数据
        byte[] arrPacket = new byte[1024];
        DatagramPacket dp = new DatagramPacket(arrPacket,arrPacket.length);
        //通过recive方法接收数据存入数据包
        ds.receive(dp);
        //通过数据包中的方法获取数据
        String ip = dp.getAddress().getHostAddress();
        String data = new String(dp.getData(),0,dp.getLength());
        int port = dp.getPort();
        System.out.println(ip+":"+data+":"+port);
        //关闭资源
        ds.close();
    }
}

你可能感兴趣的:(java)