zoukankan      html  css  js  c++  java
  • Java之数据流DataInput(Output)Stream 和 字节数组流 ByteArrayInput(Output) Stream的嵌套

    学到网络编程这一章,马老师提出了一个问题:怎样使用Java传输一个long类型的数?

    额,能力有限,所以看了答案后解析下,加深印象。

    发送端(TestUDPClient)方法如下:

    import java.net.*;
    import java.io.*;
    
    public class TestUDPClient
    {
    public static void main(String args[]) throws Exception
    {
    long n = 10000L;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    dos.writeLong(n);
    
    byte[] buf = baos.toByteArray();
    System.out.println(buf.length);
    
    DatagramPacket dp = new DatagramPacket(buf, buf.length,
    new InetSocketAddress("127.0.0.1", 5678)
    );
    DatagramSocket ds = new DatagramSocket(9999);
    ds.send(dp);
    ds.close();
    
    }
    }



    可以看到实际上java并没有提供1个封装好的方法,致使是long这个基本类型的封装类Long, 也没有提供转换为ByteArray的方法.。

    但是Java提供两个流, 它们嵌套使用的话, 就相当于实现了上面所说的功能, 将各种基本类型转换为字节数组。

    它们就是DataOutputStream 和 ByteArrayOutputStream。

    long n = 10000L;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    dos.writeLong(n);

    在这一段中,可以看到一个long类型的数通过数据流传输了出去。

    那么接收端怎样接收呢:

    import java.net.*;
    import java.io.*;
    
    public class TestUDPServer
    {
    public static void main(String args[]) throws Exception
    {
    byte buf[] = new byte[1024];
    DatagramPacket dp = new DatagramPacket(buf, buf.length);
    DatagramSocket ds = new DatagramSocket(5678);
    while(true)
    {
    ds.receive(dp);
    ByteArrayInputStream bais = new ByteArrayInputStream(buf);
    DataInputStream dis = new DataInputStream(bais);
    System.out.println(dis.readLong());
    }
    }
    }
    


    在这一段中,可以看到数据通过数据流传输了进来。

    再运用DataOutputStream 和 ByteArrayOutputStream嵌套使用后:

    ds.receive(dp);
    ByteArrayInputStream bais = new ByteArrayInputStream(buf);
    DataInputStream dis = new DataInputStream(bais);
    System.out.println(dis.readLong());

    很轻松的就拿到了long类型数据。

    实在是厉害,零散的知识就这样结合并运用了。

    不过我在想可不可以用这个方法传输任意一个object对象呢,我再试试。


  • 相关阅读:
    使用正则表达式,取得点击次数,函数抽离
    爬取校园新闻首页的新闻
    网络爬虫基础练习
    综合练习:词频统计
    【Art】虹吸原理(5月份订正版)
    【失踪人口】准初三的JZSC
    【Mood】出大问题(最近很喜欢说这句话)
    【Matrix】矩阵加法&乘法
    【C++】stdio.h和cstdio
    【Theorem】中国剩余定理
  • 原文地址:https://www.cnblogs.com/Sherlock-J/p/12926092.html
Copyright © 2011-2022 走看看