通过套接字传输byte []

时间:2015-03-26 08:04:09

标签: java android 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

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

2 个答案:

答案 0 :(得分:1)

我应该知道几点。

  • 不要将二进制文件作为文本发送。它不是文本,并且以这种方式发送二进制文件只会使其受损。
  • 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值相同的数据。你可以把它格式化。

答案 1 :(得分:0)

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

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

相关问题