Fetching the ping of a player from the server?

I am trying to get the ping of a player from the server. I am pretty sure there is no other way to do this other than using remote functions. Using remote functions however is not a good practice on the server as when you invoke a client it can infinitely yield. Is there any way to make the remote function to stop yielding after 1 second so if the ping is higher than 1000 it will just cap at 1000? I came up with this solution:

local res;
coroutine.wrap(function()
     res = RemoteFunction:InvokeClient(plr)
end)
wait(1)
if res then
      --// do something
end

I don’t know if this is a good solution and I don’t know if there are any other better ones out there. Do coroutines clean up themselves when they infinitely yield or will it cause a memory leak? Thanks in advance.

2 Likes

Coroutines will only be garbage collected if they are dead. Yielding ~= dead.

InvokeClient apparently can yield forever, so your coroutine could be a leak, yes.

Personally, I would implement this with two RemoteEvents – one the server fires to ask for a ping, and one the client fires to respond. That way, you can add your own timing logic and just ignore any late responses.

Alright, I guess that is what I am going to do. I haven’t used coroutines much in programming, AFAIK there is no way to manually kill a coroutine. Correct?

I use a remote function. Have the server script return the remote function which is true. And in the client script just calculate the elapsed time the remote function was invoked and you got yourself ping.

An example

function PING.OnServerInvoke() -- this is the remote function name
  return true
end


-- local script

while true do -- you can also use while wait do
wait()
local ping = tick()
local PING = -- wherever you have the remote function:InvokeServer() constantly invoke
if PING == true then -- it is true so we calculate le ping
-- calculate ping
  estimatedtime = tick() 
  -- subtract the estimatedtime from the ping and use some modulus operation to calculate more accurate ping
   end
wait(1) -- so as to not flood the server with constant invokes change it to whatever
end

This is for getting the ping client-side. Not relevant to my question but thanks. I guess I am going to stick with remote events. Killing a coroutine should be a feature tbh, would be very useful.

My bad but just a quick question. Wouldn’t it give you the same result? Why get the ping server sided?

There are plenty of use cases, mine is going to be displaying it to other players for a leaderboard. I am going to do what @nicemike40 suggested basically but I’ll add a few security checks in order to make sure the client can’t manipulate their ping.