Java中的
InputStream和
OutputStream类本机处理字节数组。您可能要添加的一件事是消息开头的长度,以便接收方知道期望多少字节。我通常喜欢提供一种方法,该方法可以控制字节数组中要发送的字节,这与标准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;}


