How would I measure a player’s connection?

Okay, so I have this on my scripts

image

This is my LocalScript:

local replicatedStorage = game:GetService(“ReplicatedStorage”)
local remoteEvent = replicatedStorage:WaitForChild(“RemoteEvent”)

local function ping()
local send = tick()
local ping = nil

remoteEvent:FireServer()

local receive; receive = remoteEvent.OnClientEvent:Connect(function()
ping = tick() - send
end)

wait(1)
receive:Disconnect()

return ping and math.floor(ping) or 999
end

while true do
local ping = ping()
– Ping was received by the remote within 1 second
if ping < 999 then
ping = tonumber(string.format(’%.3f’, ping*1000))
end
print(math.floor(ping)…" ms")
wait(5)
end

And this my ServerScript

local replicatedStorage = game:GetService(“ReplicatedStorage”)
local remoteEvent = replicatedStorage:WaitForChild(“RemoteEvent”)
remoteEvent.OnServerEvent:Connect(function(player)
remoteEvent:FireClient(player)
end)

I’m trying to get the player’s ping, but when testing on player, it doesn’t put anything else than repeating 0ms. Thanks.

1 Like

Hi!

Looks like your code works, but floor function (which can be used on any real number) always returns the greatest integer, which is less or equal to the given real number. Any real number lower than 1 will always return 0 and any real number between 1 and 2 will always give 1 as output.

Since units of your returned number are seconds, try to get ping by flooring returned value converted to miliseconds, which means multiplying by 1000. You can also simplify the process and use remote function, so you don’t need to fire remote event twice.

Local script:

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local remoteFunction = ReplicatedStorage:WaitForChild("RemoteFunction")

local function getPing()
	local sendTime = tick()
	remoteFunction:InvokeServer()
	local ping = tick() - sendTime
	ping = math.floor(ping * 1000)
	
	return ping and math.floor(ping) or 999
end

while (true) do
	local ping = getPing()
	print(ping)
	wait(1)
end

Server script:

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local remoteFunction = ReplicatedStorage:WaitForChild("RemoteFunction")
if (not remoteFunction) then script.Disabled = true end

remoteFunction.OnServerInvoke = function()
	return true
end

Remote function is located in replicated storage and has default name.

image

1 Like