有人可以演示如何通过 TCP 连接将字节数组从发送方程序发送到 Java 中的接收方程序。
byte[] myByteArray
(我是 Java 编程新手,似乎找不到一个示例来说明如何执行此操作来显示连接的两端(发送方和接收方)。如果您知道现有示例,也许您可以发布链接。(无需重新发明轮子。)P.S.这是不是家庭作业!:-)
最佳答案
Java 中的 InputStream
和 OutputStream
类 native 处理字节数组。您可能想要添加的一件事是消息开头的长度,以便接收者知道需要多少字节。我通常喜欢提供一种方法,该方法允许控制要发送字节数组中的哪些字节,就像标准 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;
}
关于java - 如何通过 TCP 连接发送字节数组(java 编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2878867/