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

查看:220
本文介绍了如何通过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这是 NOT 作业!: - )

(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! :-)

推荐答案

InputStream OutputStream Java中的类本身处理字节数组。您可能想要添加的一件事是消息开头的长度,以便接收器知道预期的字节数。我通常喜欢提供一种方法,允许控制字节数组中的哪些字节发送,就像标准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);
    }
}

编辑:添加接收方:

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天全站免登陆