繁体   English   中英

通过套接字传输byte []

[英]Transferring byte[] over sockets

我有一个字节数组,必须将其发送到服务器。

byte[] b=new byte[]{(byte)0xFE,0x01,0x01,0x32,0x00,0x00,(byte)0xFD};

我发送的客户代码是

PrintStream pw=new PrintStream(s.getOuputStream());
pw.Println(b);

我要接收的服务器代码是

InputStreamReader in=new InputStreamreader();
BufferedReader br=new BufferedReader(in);
String s=br.readline();
System.out.println("client sent :" + s);

当服务器接收并打印输出时,我收到client sent:[B@1f4917a7的输出client sent:[B@1f4917a7

我希望输出与发送的内容相同: FE 01 01 32 00 00 FD

我应该指出的几点。

  • 不要以文本形式发送二进制文件。 它不是文本,以这种方式发送二进制文件只会使其混乱。
  • byte[].toString()死了。 不要使用它,只会让您感到困惑。 相反,如果要打印它,则需要Arrays.toString(bytes)

我建议你试试

DataOutputStream out = new DataOutputStream(s.getOuputStream());
out.writeInt(b.length);
out.write(b);

在阅读方面

DataInputStream in = new DataInputStream(s.getInputStream());
int len = in.readInt();
byte[] bytes = new byte[len];
in.readFully(bytes);
System.out.println("Client sent: " + Arrays.toString(bytes));

这应该打印

Client sent: [ -2, 1, 1, 50, 0, 0, -3 ]

这是与十进制有符号byte值相同的数据。 您可以将其格式化以品尝。

如果要发送字节数组,则要发送二进制。 因此,没有理由使用Writer,并且有很多理由不这样做。

使用OutputStream.write(byte[])OutputStream.write(byte[],int,int).

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM