基于UDP通信的基础Demo

模拟服务端接收方代码,先运行客户端
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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值