简体   繁体   English

套接字发送和接收字节数组

[英]Socket send and receive byte array

In server, I have send a byte array to client through Java socket 在服务器中,我通过Java套接字向客户端发送了一个字节数组

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


Receiver: 接收器:

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
}

First, do not use DataOutputStream unless it's really necessary. 首先,除非确实需要,否则不要使用DataOutputStream Second: 第二:

Socket socket = new Socket("host", port);
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(message);

Of course this lacks any error checking but this should get you going. 当然这没有任何错误检查,但这应该让你去。 The JDK API Javadoc is your friend and can help you a lot. JDK API Javadoc是您的朋友,可以为您提供很多帮助。

There is a JDK socket tutorial here , which covers both the server and client end. 有一个JDK插座教程在这里 ,它涵盖了服务器和客户端。 That looks exactly like what you want. 这看起来完全像你想要的。

(from that tutorial) This sets up to read from an echo server: (来自该教程)这设置为从echo服务器读取:

    echoSocket = new Socket("taranis", 7);
    out = new PrintWriter(echoSocket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(
                                echoSocket.getInputStream()));

taking a stream of bytes and converts to strings via the reader and using a default encoding (not advisable, normally). 获取字节流并通过阅读器转换为字符串并使用默认编码(通常不建议)。

Error handling and closing sockets/streams omitted from the above, but check the tutorial. 从上面省略了错误处理和关闭套接字/流,但请查看教程。

You need to either have the message be a fixed size, or you need to send the size or you need to use some separator characters. 您需要将消息设置为固定大小,或者需要发送大小,或者需要使用一些分隔符。

This is the easiest case for a known size (100 bytes): 对于已知大小(100字节),这是最简单的情况:

in = new DataInputStream(server.getInputStream());
byte[] message = new byte[100]; // the well known size
in.readFully(message);

In this case DataInputStream makes sense as it offers readFully() . 在这种情况下, DataInputStream是有意义的,因为它提供了readFully() If you don't use it, you need to loop yourself until the expected number of bytes is read. 如果不使用它,则需要循环自己,直到读取预期的字节数。

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

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