Table of Contents

Class WebSocketHandler

Namespace
WitShells.WebSocket

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

WebSocketBinaryEvent

OnConnectionClosed

public UnityEvent OnConnectionClosed

Field Value

UnityEvent

OnConnectionOpened

public UnityEvent OnConnectionOpened

Field Value

UnityEvent

OnError

public WebSocketStringEvent OnError

Field Value

WebSocketStringEvent

OnTextMessageReceived

public WebSocketStringEvent OnTextMessageReceived

Field Value

WebSocketStringEvent

Properties

State

Current state of the WebSocket connection.

public WebSocketState State { get; }

Property Value

WebSocketState

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

settings ConnectionSettingsObject

Connection configuration settings

pathOverride string

Optional path to override the default path (e.g., "/api/websocket")

protocolIndex int

Index 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

data byte[]

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

message string

Text message to send

Returns

bool

True if message was sent successfully, false otherwise