PAC3-Server / notagain

Custom Servercontent for the official PAC3 Server.
GNU General Public License v3.0
13 stars 22 forks source link

crashsystems (player reconnect) #99

Closed Techbot121 closed 7 years ago

Techbot121 commented 7 years ago

Right now if the Server crashes people have to manually reconnect.

NanoAi commented 7 years ago

Started a rough draft, here's the code so far... moved down

NanoAi commented 7 years ago

Updates!

if SERVER then
    util.AddNetworkString("pingpong")

    local loaded = {}

    hook.Add("PlayerCanHearPlayersVoice", "pingpong", function(ply)
        if not table.HasValue(loaded,ply) then
            table.insert(loaded, ply)
        end
    end)

    hook.Add("PlayerDisconnected", "pingpong", function(ply)
        table.RemoveByValue(loaded, ply)
    end)

    timer.Create("pingpong", 0.5, 0, function()
        net.Start("pingpong", true)
        net.Send(loaded)
    end)

else
    local API_RESPONSE
    local api = string.format("https://api.steampowered.com/ISteamApps/GetServersAtAddress/v1/?addr=%s&format=json", tostring( game.GetIPAddress() ))

    local RealTime = RealTime
    local hookAdd = hook.Add
    local hookRun = hook.Run

    local lastPong
    local pong = 0

    net.Receive("pingpong", function()
        if pong < 5 then
            pong = pong + 1
        else
            lastPong = RealTime()
        end
    end)

    local function pong()
        if lastPong then
            lastPong = RealTime()
        end
    end
    hookAdd("Move", "pingpong", pong)
    hookAdd("VehicleMove", "pingpong", pong)

    hookAdd("Tick", "pingpong", function() 
        if not lastPong then return end

        local timeout = RealTime() - lastPong

        if timeout > 1.1 then
            hookRun("CrashTick", true, timeout + 1.1, API_RESPONSE)
        else
            hookRun("CrashTick", false)
        end
    end)

    local function checkServer()
        http.Fetch(api,
            function( body, len, headers, code )
                local data = util.JSONToTable(body)
                if data and next(data) then
                    API_RESPONSE = 1 -- Attempting Reconnect.
                    data = data["response"] and data["response"]["servers"]
                    if data and next(data) then
                        if data[1]["addr"] then
                            API_RESPONSE = 4 -- Server Is Up Again
                        end
                    else
                        API_RESPONSE = 2 -- Server Not Responding.
                    end
                else
                    API_RESPONSE = 2 -- Server Not Responding.
                end
            end,
            function( error )
                API_RESPONSE = 3 -- No Internet Connection or API Down.
            end
        )
    end
end