如何通过TCP连接发送字节数组(java编程)

Mar*_*rts 25 java sockets tcp bytearray

有人可以演示如何通过TCP连接从发送器程序向Java中的接收器程序发送字节数组.

byte[] myByteArray
Run Code Online (Sandbox Code Playgroud)

(我是Java编程的新手,似乎无法找到如何执行此操作的示例,显示连接的两端(发送方和接收方).如果您知道现有示例,也许您可​​以发布链接(不需要重新发明轮子.)PS这不是功课!:-)

Kev*_*ock 56

Java中的InputStreamOutputStream本地处理字节数组.您可能想要添加的一件事是消息开头的长度,以便接收器知道预期的字节数.我通常喜欢提供一种方法,允许控制字节数组中的哪些字节发送,就像标准API一样.

像这样的东西:

private Socket socket;

public void sendBytes(byte[] myByteArray) throws IOException {
    sendBytes(myByteArray, 0, myByteArray.length);
}

public void sendBytes(byte[] myByteArray, int start, int len) throws IOException {
    if (len < 0)
        throw new IllegalArgumentException("Negative length not allowed");
    if (start < 0 || start >= myByteArray.length)
        throw new IndexOutOfBoundsException("Out of bounds: " + start);
    // Other checks if needed.

    // May be better to save the streams in the support class;
    // just like the socket variable.
    OutputStream out = socket.getOutputStream(); 
    DataOutputStream dos = new DataOutputStream(out);

    dos.writeInt(len);
    if (len > 0) {
        dos.write(myByteArray, start, len);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:添加接收方:

public byte[] readBytes() throws IOException {
    // Again, probably better to store these objects references in the support class
    InputStream in = socket.getInputStream();
    DataInputStream dis = new DataInputStream(in);

    int len = dis.readInt();
    byte[] data = new byte[len];
    if (len > 0) {
        dis.readFully(data);
    }
    return data;
}
Run Code Online (Sandbox Code Playgroud)