基于UDP通信的基础Demo

本文通过客户端和服务端的Java代码示例展示了如何使用UDP协议传输double类型的数据。客户端负责将double类型的数据转换为字节数组并发送,而服务端则接收这些字节并将其重新转换为原始的double数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模拟服务端接收方代码,先运行客户端
public class DoubleMyServer {

    public static void main(String[] args) {
        try {
            DatagramSocket server = new DatagramSocket(8888);
            byte[]container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container,container.length);
            server.receive(packet);
            double num =convert(packet.getData());
            System.out.println(num);
            //释放资源
            server.close();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 接收方将数据转化为double
     * @param data
     * @return
     */
    public static double convert(byte[]data){
        DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
        double num = 0;
        try {
             num = dis.readDouble();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return num;
    }

}
模拟客户端接收方代码
public class DoubleMyClient {

    public static void main(String[] args) {
        try {
            DatagramSocket client =new DatagramSocket(6666);
            double num =58.12;
            byte[]data =convert(num);
            DatagramPacket packet = new DatagramPacket(data,data.length,new InetSocketAddress("localhost",8888));
            client.send(packet);
            client.close();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 将double数据转换成字节数组输出流
     * @param dob
     * @return
     */
    public static byte[] convert(double num){
        byte[]data=null;
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                DataOutputStream dos = new DataOutputStream(bos);
                dos.writeDouble(num);
                dos.flush();
                data=bos.toByteArray();
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        return data;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值