如何通过 TCP 连接发送字节数组(java 编程) [英] how to send an array of bytes over a TCP connection (java programming)

查看:32
本文介绍了如何通过 TCP 连接发送字节数组(java 编程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can somebody demonstrate how to send an array of bytes over a TCP connection from a sender program to a receiver program in Java.

byte[] myByteArray

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

(I'm new to Java programming, and can't seem to find an example of how to do this that shows both ends of the connection (sender and receiver.) If you know of an existing example, maybe you could post the link. (No need to reinvent the wheel.) P.S. This is NOT homework! :-)

推荐答案

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

The InputStream and OutputStream classes in Java natively handle byte arrays. The one thing you may want to add is the length at the beginning of the message so that the receiver knows how many bytes to expect. I typically like to offer a method that allows controlling which bytes in the byte array to send, much like the standard 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);
    }
}

EDIT:添加接收方:

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

这篇关于如何通过 TCP 连接发送字节数组(java 编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆