Skip to content

Instantly share code, notes, and snippets.

@Nrjwolf
Last active August 23, 2020 09:05
Show Gist options
  • Save Nrjwolf/bf05196bd4f9d5f47d910e626997350a to your computer and use it in GitHub Desktop.
Save Nrjwolf/bf05196bd4f9d5f47d910e626997350a to your computer and use it in GitHub Desktop.
Connection checker
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class NetworkConnectionChecker : MonoBehaviour
{
[Header("Settings")]
public bool RunOnStart = true;
public string DefaultChekingServer = "https://google.com";
public float CheckPeriod = 5;
public float ErrorRetryDelay = 15;
[Header("Debug")]
public bool IsDebugOnInDevBuild = true;
public Color GUIColorConnected = Color.green;
public Color GUIColorNotConnected = Color.red;
[SerializeField]
private bool m_IsConnected;
public bool IsConnected
{
get => m_IsConnected;
private set
{
if (m_IsConnected != value)
{
m_IsConnected = value;
OnNetworkConnectivityChanged?.Invoke(m_IsConnected);
}
}
}
public Action<bool> OnNetworkConnectivityChanged;
#region Unity
private void Start()
{
if (RunOnStart)
RunCheckerProcess();
}
private void OnGUI()
{
if (Debug.isDebugBuild)
{
GUI.matrix = Matrix4x4.Scale(new Vector3(3.5f, 3.5f, 3.5f));
GUI.color = IsConnected ? GUIColorConnected : GUIColorNotConnected;
GUI.Label(new Rect(0, 0, 200, 50), IsConnected ? "Connected" : "Not connected");
}
}
#endregion
#region Public
public void RunCheckerProcess() => StartCoroutine(CheckerProcess());
public void CheckInternetConnection(Action<bool> result) => CheckInternetConnectionForServer(DefaultChekingServer, result);
public void CheckInternetConnectionForServer(string server, Action<bool> result) => StartCoroutine(CheckInternetConnectionCoroutine(server, result));
#endregion
#region Private
private IEnumerator CheckerProcess()
{
bool connection = false;
yield return StartCoroutine(CheckInternetConnectionCoroutine(DefaultChekingServer, (result) => connection = result));
IsConnected = connection;
if (IsConnected)
{
yield return new WaitForSeconds(CheckPeriod);
RunCheckerProcess();
}
else
{
yield return new WaitForSeconds(ErrorRetryDelay);
RunCheckerProcess();
}
}
private IEnumerator CheckInternetConnectionCoroutine(string server, Action<bool> syncResult)
{
bool result;
using (var request = UnityWebRequest.Head(server))
{
request.timeout = 5;
yield return request.SendWebRequest();
result = !request.isNetworkError && !request.isHttpError && request.responseCode == 200;
}
syncResult(result);
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment