当前位置: 首页 > 面试题库 >

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

佘缪文
2023-03-14
问题内容

有人可以演示如何使用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;
}


 类似资料:
  • 我已经在两台计算机之间建立了一个TCP连接,用于在windows应用程序中来回发送和接收数据。我正在发送的消息是一组被转换为字符串并被“,”拆分的整数。所以,为了发送我要使用的数据, 如果有人能给我解释一下就好了,因为我对C#的网络方面也相当陌生。 跟进问题:StreamReader没有停止阅读C#

  • 我需要通过Java socket发送一个文本消息到服务器,然后发送一个字节数组,然后是一个字符串等等。到目前为止,我所开发的内容还在工作,但客户端只读取发送的第一个字符串。 从服务器端:我使用发送字节数组,使用发送字符串。 问题是客户机和服务器不同步,我的意思是服务器发送字符串然后字节数组然后字符串,而不等待客户机消耗每个需要的字节。 我的意思是情况不是这样的:

  • 我在JAVA中通过TCP接收字节数据包时遇到了一些问题。我的TCPServer类发送207字节的数据包。当我发送一个数据包时,控制台中的程序显示“读取207字节的数据包”然后停下来。在下一个数据包继续执行时,显示“多重测量”和“读取1868767867字节数据包”。之后,接收将永远停止。我不知道它为什么接收1868767867字节。我在wireshark中检查它,服务器总是发送207字节。 这是我

  • 我有一个数组类型的。我必须在python中通过流/TCP套接字发送它。然后我必须在接收端接收相同的阵列。

  • 我有一个关于在Android中发送字节数组的问题。 我以前试图使用Android httpclient文件上传数据损坏和超时问题 但是,我真的不知道如何使用它。。。。。。 在我的项目中,我之前使用NameValuePair列表将String类型的数据发送到Apache服务器,例如 在 post 方法中(DB_Packet是字符串变量) list name value pair = new Arra

  • 出于某些原因,我需要通过服务器套接字分别发送多个字节数组,客户端套接字将接收这些字节数组。发送字节数组后,发现客户端套接字接收的字节数组与服务器套接字接收的字节数组不相等。如果我使用ObjectOutputStream和ObjectInputStream,那么一切都很好,但是根据我的需要,我不能使用ObjectOutputStream和ObjectInputStream,因为我的服务器需要连接两个