Based on NativeWebSocket
Analog for the backend: extented-ws
This is a websocket wrapper for Unity designed to process JSON messages
The observer-handlers approach is used, like in FastAPI and Aiogram it's allows you to quickly integrate web sockets into the project, and expand the list of requests-responses
Requires Unity 2019.1+ with .NET 4.x+ Runtime
- Open Unity
- Open Package Manager Window
- Click Add Package From Git URL
- Enter URL:
https://github.com/endel/NativeWebSocket.git#upm
- Repert with URL:
https://github.com/dexsper/UnityWebsocketsObserver.git
- Download this project
- Copy the sources from WebsocketsObserver into your Assets directory.
Singleton
- Drop class
SingletonWebsocketsObserver
on gameobject in scene - Set websokets url
- Use
SingletonWebsocketsObserver.Instance
{
"Type": "CalculateRequest",
"Data": {
"Numbers": [2, 2]
}
}
{
"Type": "CalculateResponse",
"Data": {
"Result": 4
}
}
using WebsocketsObserver;
using WebsocketsObserver.Request;
public struct CalculateResponse : IServerMessage
{
public int Result { get; set; }
}
public struct CalculateRequest : IClientRequest
{
public int[] Numbers { get; set; }
}
public class Test : MonoBehaviour
{
private void Start()
{
var observerInstance = SingletonWebsocketsObserver.Instance;
observerInstance.RegisterHandler(OnCalculated);
observerInstance.SendRequest(new CalculateRequest
{
Numbers = new int[2] { 2, 2 }
});
}
private void OnCalculated(CalculateResponse response)
{
}
}