Class WebSocketHandler
A Unity WebSocket client component that provides easy integration with Unity's event system. Handles connection management, message sending/receiving, and provides Unity Events for all operations.
public class WebSocketHandler : MonoBehaviour
- Inheritance
-
WebSocketHandler
Fields
OnBinaryDataReceived
public WebSocketBinaryEvent OnBinaryDataReceived
Field Value
OnConnectionClosed
public UnityEvent OnConnectionClosed
Field Value
- UnityEvent
OnConnectionOpened
public UnityEvent OnConnectionOpened
Field Value
- UnityEvent
OnError
public WebSocketStringEvent OnError
Field Value
OnTextMessageReceived
public WebSocketStringEvent OnTextMessageReceived
Field Value
Properties
State
Current state of the WebSocket connection.
public WebSocketState State { get; }
Property Value
Methods
Close()
Gracefully closes the WebSocket connection.
public void Close()
Connect()
Initiates a connection to the WebSocket server. Must call Initialize() first before attempting to connect.
public void Connect()
Exceptions
- InvalidOperationException
Thrown when WebSocket is not initialized
Initialize(ConnectionSettingsObject, string, int)
Initializes the WebSocket connection with the specified settings.
public void Initialize(ConnectionSettingsObject settings, string pathOverride = null, int protocolIndex = -1)
Parameters
settingsConnectionSettingsObjectConnection configuration settings
pathOverridestringOptional path to override the default path (e.g., "/api/websocket")
protocolIndexintIndex of the protocol to use from settings, or -1 for default
Exceptions
- ArgumentNullException
Thrown when settings is null
SendBinaryData(byte[])
Sends binary data to the WebSocket server.
public bool SendBinaryData(byte[] data)
Parameters
databyte[]Binary data to send
Returns
- bool
True if data was sent successfully, false otherwise
SendTextMessage(string)
Sends text message to the WebSocket server.
public bool SendTextMessage(string message)
Parameters
messagestringText message to send
Returns
- bool
True if message was sent successfully, false otherwise