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


问题内容

有人可以演示如何使用Java通过TCP连接从发送方程序向接收方程序发送字节数组。

byte[] myByteArray

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


问题答案:

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);
    }
}

编辑 :要添加接收方:

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;
}