socket中传输byte数组数据

时间:2025-01-25 08:11:49

客户端:

private Socket socket;
private DataOutputStream out;

out = new DataOutputStream(()); 
byte[] bytes = { 0x03,0x02,0x01 };
(bytes);
服务器端:
private Socket clientSocket;
private DataInputStream in;

in = new DataInputStream(());
// 定义一个byte数组用来存放读取到的数据,byte数组的长度要足够大。
byte[] bytes = new byte[100];
(bytes);// 把输入流的数据写入bytes数组中。再依次读取出来即可

String string = new String(bytes,index,length);
Integer integer = new Integer(new String(bytes,index,length));
// 将byte数组中从第index个开始的length个长度的字节转化为string型。
// new String(byte)是将整个byte数组转化为string型。

注:socketClient的输出流 和 socketServer的输入流必须为同一种流(如:DataInputSteam和DataOutputSteam、InputSteam和OutputSteam)
上面的DataOutputStream传输的流以字节的形式存放到了byte数组,再利用new String方法就可以将其转化为string型了。利用PrintWriter相对于繁琐,封装了很多方法在byte和string之间转化不便。
参考:/s/blog_a4bfe8c90101dpst.html