套接字发送和接收字节数组 [英] Socket send and receive byte array
本文介绍了套接字发送和接收字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在服务器中,我通过Java套接字向客户端发送了一个字节数组
In server, I have send a byte array to client through Java socket
byte[] message = ... ;
DataOutputStream dout = new DataOutputStream(client.getOutputStream());
dout.write(message);
如何从客户端接收此字节数组?
How can I receive this byte array from client?
推荐答案
试试这个,它对我有用。
发件人:
Try this, it's working for me.
Sender:
byte[] message = ...
Socket socket = ...
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeInt(message.length); // write length of the message
dOut.write(message); // write the message
接收者:
Socket socket = ...
DataInputStream dIn = new DataInputStream(socket.getInputStream());
int length = dIn.readInt(); // read length of incoming message
if(length>0) {
byte[] message = new byte[length];
dIn.readFully(message, 0, message.length); // read the message
}
这篇关于套接字发送和接收字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文