111 lines
3.1 KiB
C#
111 lines
3.1 KiB
C#
using MikeSchweitzer.WebSocket;
|
|
using UnityEngine;
|
|
using System.Collections;
|
|
using UnityEngine.SceneManagement;
|
|
|
|
public class WebsocketHandler : MonoBehaviour
|
|
{
|
|
public static WebsocketHandler Instance;
|
|
public WebSocketConnection _Connection;
|
|
|
|
private bool isReconnecting = false;
|
|
private bool intentionalDisconnect = false;
|
|
|
|
private static readonly WaitForSeconds _waitForSeconds2 = new(2f);
|
|
private string lastSceneName = null;
|
|
|
|
private void Awake()
|
|
{
|
|
if (Instance != null)
|
|
{
|
|
Destroy(gameObject);
|
|
return;
|
|
}
|
|
|
|
Instance = this;
|
|
DontDestroyOnLoad(gameObject);
|
|
|
|
_Connection = gameObject.AddComponent<WebSocketConnection>();
|
|
_Connection.DesiredConfig = new WebSocketConfig
|
|
{
|
|
MaxReceiveBytes = 10 * 1024 * 1024
|
|
};
|
|
_Connection.StateChanged += OnStateChanged;
|
|
_Connection.ErrorMessageReceived += OnErrorMessageReceived;
|
|
|
|
SceneManager.sceneLoaded += OnSceneLoaded;
|
|
|
|
Connect();
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
if (_Connection != null)
|
|
{
|
|
_Connection.StateChanged -= OnStateChanged;
|
|
_Connection.ErrorMessageReceived -= OnErrorMessageReceived;
|
|
}
|
|
}
|
|
|
|
public void Connect()
|
|
{
|
|
intentionalDisconnect = false;
|
|
|
|
if (_Connection.State == WebSocketState.Connected || _Connection.State == WebSocketState.Connecting) return;
|
|
|
|
_Connection.Connect(Endpoints.WS_ENDPOINT);
|
|
}
|
|
|
|
public void Disconnect()
|
|
{
|
|
intentionalDisconnect = true;
|
|
_Connection.Disconnect();
|
|
}
|
|
|
|
private void OnStateChanged(WebSocketConnection connection, WebSocketState oldState, WebSocketState newState)
|
|
{
|
|
Debug.Log($"WS state changed from \"{oldState}\" to \"{newState}\"");
|
|
if (newState == WebSocketState.Disconnected && !intentionalDisconnect && !isReconnecting)
|
|
{
|
|
StartCoroutine(ReconnectWithDelay());
|
|
}
|
|
if (newState == WebSocketState.Connected)
|
|
{
|
|
var currentSceneName = SceneManager.GetActiveScene().name;
|
|
ConnectedWithCurrentSceneMessage msg = new()
|
|
{
|
|
sceneName = currentSceneName
|
|
};
|
|
_Connection.AddOutgoingMessage(JsonUtility.ToJson(msg));
|
|
}
|
|
}
|
|
|
|
private void OnErrorMessageReceived(WebSocketConnection connection, string errorMessage)
|
|
{
|
|
Debug.LogError($"WS error {errorMessage}");
|
|
}
|
|
|
|
private IEnumerator ReconnectWithDelay()
|
|
{
|
|
isReconnecting = true;
|
|
yield return _waitForSeconds2;
|
|
isReconnecting = false;
|
|
Debug.Log("Trying to connect again");
|
|
Connect();
|
|
}
|
|
|
|
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
|
|
{
|
|
if (_Connection.State == WebSocketState.Connected)
|
|
{
|
|
SceneChangeMessage msg = new()
|
|
{
|
|
to = scene.name,
|
|
from = lastSceneName
|
|
};
|
|
_Connection.AddOutgoingMessage(JsonUtility.ToJson(msg));
|
|
}
|
|
lastSceneName = scene.name;
|
|
}
|
|
}
|