Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting byte arrays using TCP connections

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 and noticed that instead of using DatagramPacket like UDP, TCP uses InputStream/OutputStream.

How do we get the byte[] from DataInputStream, something that's similar to this:

byte[] receiveData = new byte[64000];
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length); 
receiveData=receivePacket.getData();
like image 294
Dao Lam Avatar asked Dec 01 '22 05:12

Dao Lam


1 Answers

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;
}
like image 54
jtahlborn Avatar answered Dec 02 '22 18:12

jtahlborn