Getting byte arrays using TCP connections

前端 未结 2 1345
清酒与你
清酒与你 2021-01-19 14:49

I was using UDP to send/receive data but I now want to switch to TCP to avoid packet loss.

I\'ve read several tutorials on TCP

2条回答
  •  终归单人心
    2021-01-19 15:43

    in order to implement a message based protocol over a socket (stream), you basically want to come up with some message format, then read/write that on either end of the connection. a very simple format is to write the length of the message as a 4 byte int, then send the message bytes (then flush the stream). on the receiving end, read a 4 byte int, then read exactly that many following bytes (be careful that you limit your read method call or you may accidentally read part of the next message).

    public void writeMessage(DataOutputStream dout, byte[] msg, int msgLen) {
      dout.writeInt(msgLen);
      dout.write(msg, 0, msgLen);
      dout.flush();
    }
    
    public byte[] readMessage(DataInputStream din) {
      int msgLen = din.readInt();
      byte[] msg = new byte[msgLen];
      din.readFully(msg);
      return msg;
    }
    

提交回复
热议问题