Search code examples
javanetwork-programmingtcpip

TCP Client message acumulating


I´m trying to implement a TCP client that sends to a server each 50ms. So I`ve developed a quick TCP test program where I can change the time between each message and I don't really get the message to send each X ms and they are accumulating as you can see at the Wireshark capture. Any ideas?

It is supposed to be only one letter a and Time since the previous frame in this TCP stream should be near to the value introduced by the console in this example 0.08 seconds

enter image description here

public class TCPClient {

static Socket clientSocket;
static DataOutputStream outToServer;
public static class enviar extends TimerTask {
    public void run() {
        try{
            outToServer.writeBytes("a");
            System.out.println("Packet Sent");
        }catch(Exception e){
            System.out.println(e);
        }
    }
}



public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int tiempo = 1000;
    System.out.print("Tiempo: ");
    tiempo = scanner.nextInt();
    try{
        clientSocket = new Socket("192.168.1.21", 1337);
        outToServer = new DataOutputStream(clientSocket.getOutputStream());
    }catch(Exception e){
        System.out.println(e);
    }
    Timer timer = new Timer();
    timer.schedule(new enviar(), 0, tiempo);
}

}


Solution

  • You can affect the sender behavior by setting the socket option "TCP_NODELAY" (local spelling may vary), which makes it more likely that the bytes will be sent immediately (subject to flow control, etc) but that does not change the underlying nature of TCP.

    TCP is not a message-oriented protocol, it is a sequential byte-stream protocol. There is no guarantee that separate execution of 'send' results in the same number, with the same content, of 'receives' at the other end. It often happens especially on LANs that you get unlucky and 'message' boundaries appear to be preserved, but it ain't necessarily so.

    If you want messages, you have to invent them. Standard techniques: fixed-length messages (sounds like you're doing this: length 1), a header giving the length, delimiter bytes. The receiver has to be coded to reconstruct the messages. The on-the-wire packetization does not matter.