A simple websocket package for the Unity Game Engine.
Requires Unity 2021.3 LTS or higher.
The recommended installation method is though the unity package manager and OpenUPM.
- Open your Unity project settings
- Select the
Package Manager
- Add the OpenUPM package registry:
- Name:
OpenUPM
- URL:
https://package.openupm.com
- Scope(s):
com.utilities
- Name:
- Open the Unity Package Manager window
- Change the Registry from Unity to
My Registries
- Add the
Utilities.Websockets
package
- Open your Unity Package Manager
- Add package from git url:
https://github.com/RageAgainstThePixel/com.utilities.websockets.git#upm
Note: this repo has dependencies on other repositories! You are responsible for adding these on your own.
To setup a new connection, create a new instance of WebSocket and subscribe to event callbacks, and call Connect
or ConnectAsync
methods.
Important
WebSocket implements IDisposable
and should be properly disposed after use!
var address = "wss://echo.websocket.events";
using var socket = new WebSocket(address);
socket.OnOpen += () => Debug.Log($"Connection Established @ {address}");
socket.OnMessage += (dataFrame) => {
switch (dataFrame.Type)
{
case OpCode.Text:
AddLog($"<- Received: {dataFrame.Text}");
break;
case OpCode.Binary:
AddLog($"<- Received: {dataFrame.Data.Length} Bytes");
break;
}
};
socket.OnError += (exception) => Debug.LogException(exception);
socket.OnClose += (code, reason) => Debug.Log($"Connection Closed: {code} {reason}");
socket.Connect();
Note
socket.ConnectAsync()
is blocking until the connection is closed.
You can subscribe to the OnOpen
, OnMessage
, OnError
, and OnClose
events to handle respective situations:
Event triggered when the WebSocket connection has been established.
socket.OnOpen += () => Debug.Log("Connection Established!");
Event triggered when the WebSocket receives a message. The callback contains a data frame, which can be either text or binary.
socket.OnMessage += (dataFrame) => {
switch (dataFrame.Type)
{
case OpCode.Text:
AddLog($"<- Received: {dataFrame.Text}");
break;
case OpCode.Binary:
AddLog($"<- Received: {dataFrame.Data.Length} Bytes");
break;
}
};
Event triggered when the WebSocket raises an error. The callback contains an exception which can be handled, re-thrown, or logged.
socket.OnError += (exception) => Debug.LogException(exception);
Event triggered when the WebSocket connection has been closed. The callback contains the close code and reason.
socket.OnClose += (code, reason) => Debug.Log($"Connection Closed: {code} {reason}");
Perfect for sending json payloads and other text messages.
await socket.SendAsync("{\"message\":\"Hello World!\"}");
Perfect for sending binary data and files.
var bytes = System.Text.Encoding.UTF8.GetBytes("Hello World!");
await socket.SendAsync(bytes);
To disconnect from the server, use Close
or CloseAsync
methods and dispose of the WebSocket.
socket.Close();
socket.Dispose();