java 套接字数据输入流

java socket DataInputStream

我有一个多线程程序 java java 套接字,我收到了奇怪的信息。 像这样 234567189002636787222222222222222之间]

public void run() 
       {
            try {

                byte[] bs = new byte[64];

                 // read data into buffer
                 dataReception.read(bs);

                 // for each byte in the buffer
                 for (byte b:bs)
                 {
                    // convert byte into character
                    char c = (char)b;

                    // print the character
                    System.out.print(c);
                 }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

问题在这里:

// read data into buffer
dataReception.read(bs);

Read 读取的字节数不完全是您希望在该数组中拥有的字节数。它可以读取 any 个字节。因此,您总是 必须检查读取操作的return 值;并且只有当所有预期的字节都被读取时......你应该继续!

你的输出看起来像垃圾的原因是不是你会收到特殊字符。

发生的事情是:

  • 您创建了一个新数组(用零值初始化)。
  • 然后您读取了一些字节,很可能没有足够的字节来填充该数组。
  • 第一次读取后,打印现在包含初始零值的数组;和一些类似于可打印字符的字节。

这可以通过在阅读之前打印数组来验证。您会看到它只包含 "special" 个字符。

尝试:

public void run() 
       {
            try {

                byte[] bs = new byte[64];

                 // read data into buffer
                 int readed = dataReception.read(bs);

                 // for each byte in the buffer
                 for (int n=0; n<readed;n++)

                 {
                    byte b=bs[n];

                    // convert byte into character
                    char c = (char)b;

                    // print the character
                    System.out.print(c);
                 }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

如果您期望恰好有 64 个字节,请使用 readFully() 而不是 read(), 或者至少注意它的 return 值。

DataInputStream 通常在需要通过套接字共享文本信息时使用。如果传输的数据是使用 DataOutputStream.writeUTF(String str) 从另一端发送的,请使用 DataInputStream.readUTF() 方法。 DataInputStream 和 DataOutputStream 在发送实际数据之前发送两个字节(无符号)长度的数据。

final String data = din.readUTF();