Isaac Phillips
Isaac Phillips

Reputation: 57

How to send packets at a precise interval

For a game I'm developing using Unity I have a server which sends packets to clients at an interval of 50ms per packet.

    float time; 
    float packetDelay = 0.05f 

    private void Update()
    {
        time += Time.deltaTime; 

        if (time > packetDelay)
        {
            // send packet 
            time = 0f; 
        }
    }

The problem is when I'm checking the actual intervals it's at around .058 - .06 per packet. I have my clients syncing up their time to the servers time and I want it to be able to predict the servers packet number by time / packetDelay, which wont work with the intervals being inconsistent.

Upvotes: 0

Views: 428

Answers (1)

Erik Overflow
Erik Overflow

Reputation: 2306

Unfortunately, you cannot precisely time the interval between executions. This is especially the case in the Update() method, as this method's rate of execution is determined by your framerate. On top of that, networks are not consistent. The same code execution and packet can take a significantly different amount of time based on the state of your connection, or the network in general.

I would agree with Franck's comment. I would suggest finding another solution to this problem. Rather than setting predicting the packet order, I would recommend including the packet number as a part of the payload.

Upvotes: 1

Related Questions