A script serves as template of WebSocket in Unity.
WebSocketUtility is a utility class written in C# for Unity that provides functionality for establishing and managing WebSocket connections. It allows sending and receiving messages over the WebSocket protocol.
- Connect to a WebSocket server using a specified URI.
- Send messages to the server.
- Receive messages from the server.
- Handle received JSON data.
- Implement heartbeat functionality to check the connection status.
- Create an instance of the WebSocketUtility class by providing the WebSocket server URI.
Uri serverUri = new Uri("wss://example.com");
WebSocketUtility wsUtility = new WebSocketUtility(serverUri);
- Connect to the WebSocket server.
wsUtility.Connect();
- Send messages to the server.
string message = "Hello, server!";
wsUtility.Send(message);
- Handle received JSON datab by
subscribing to theregistering callback with protocol.OnReceiveJson
event.
wsUtility.RegisterProtocolCallback("HELLO_WORLD", HelloWorld);
private void HelloWorld(string data)
{
// Process the received JSON data
}
- Disconnect from the WebSocket server.
wsUtility.Disconnect();
- UnityEngine
- System.Net.WebSockets
- System.Text
- System.Threading
- SimpleJSON
- Newtonsoft.Json
- OverwatchLogger
- You may notice HttpManager (from Biozone.Networking). It's just an empty Monobehaviour whose mission is host coroutines. You can replace it with your own.