Guides

WebSockets

WebSocket clients (ws:// and wss://) that reconnect on their own, with every callback on the main thread.

ISource2ModWebSockets opens WebSocket connections to your backend: a live feed, a panel that pushes commands to the server, a relay between servers. Steam has no WebSocket client, so these run on the core's own network thread. Your plugin never sees that thread: everything a socket reports reaches you on the main thread, and a socket goes away with the plugin that opened it.

plugin.cpp
#include "source2mod/ISource2ModWebSockets.h"

Opening a socket

plugin.cpp
class Feed : public ISource2ModWebSocketListener
{
public:
    void OnWebSocketOpen(ISource2ModWebSocket* socket, bool reconnected) override
    {
        socket->Send(R"({"type":"hello","server":"eu-1"})");
    }

    void OnWebSocketMessage(ISource2ModWebSocket* socket, const char* data, size_t length, bool binary) override
    {
        // data is valid only during this call: copy what you keep.
        if (!binary)
            HandleCommand(std::string(data, length));
    }

    void OnWebSocketClose(ISource2ModWebSocket* socket, int code, const char* reason) override
    {
        // Lost (1006) or closed by the server: it reconnects on its own.
    }

    void OnWebSocketError(ISource2ModWebSocket* socket, const char* error) override
    {
        g_pSource2ModAPI->ConPrintf("feed: %s\n", error);
    }
};

Feed g_feed;
ISource2ModWebSocket* g_pFeed = nullptr;

bool Plugin::Load(ISource2ModAPI* api, char* error, size_t maxlen, bool late)
{
    // ...
    Source2ModWebSocketOptions options;
    options.m_Headers = { { "Authorization", "Bearer " + g_ApiToken } };
    g_pFeed = g_pSource2ModWebSockets->Connect("wss://api.example.com/feed", &g_feed, options);
    return true;
}

Connect() returns at once with the socket Connecting; OnWebSocketOpen follows when the handshake is through. It returns nullptr (null in SourcePawn) for a URL that is not ws:// or wss://.

Every listener method is optional. The plugin whose code the listener class lies in owns the socket, the same way HTTP reads it off the callback. In SourcePawn only onMessage is required, and the data cell rides along to every callback.

Options

Source2ModWebSocketOptionsSourcePawn argumentDefaultMeaning
m_HeadersheadersnoneExtra headers on the opening handshake (Authorization, cookies ...)
m_bAutoReconnectautoReconnecttrueOpen the connection again when it is lost
m_nPingIntervalSecpingInterval30Seconds without traffic before a ping. After twice that with no traffic, the connection counts as lost. 0 turns pings off
m_bVerifyPeerverifyPeertrueCheck a wss:// server's certificate against the system's CA store. Turn it off only for a test server with a self-signed certificate
m_nMaxMessageSizenone16 MBA larger message drops the connection

Sending and closing

C++SourcePawn
Send(text)Send(text)A text message. Queued in order; false while the socket is not Open
SendBinary(data, length)SendBinary(data, length)A binary message, zeros allowed
Close(code, reason)Close(code, reason)A close handshake. The socket is not opened again, and OnWebSocketClose reports when it is done
GetState()StateConnecting, Open or Closed
GetUrl()GetUrl(buffer, maxlen)
Destroy()delete socketCloses the connection and frees the socket. Nothing more is called, not even OnWebSocketClose

Destroy() (delete) is safe from inside one of the socket's own callbacks.

Reconnecting

When a connection is lost, with no close frame (code 1006) or because the server closed it, OnWebSocketClose runs. The socket then goes back to Connecting and tries again after 1 second. The wait doubles after every failed attempt, up to 30 seconds. When it is back, OnWebSocketOpen runs with reconnected set, which is the place to log in or subscribe again. OnWebSocketError reports each failed attempt (refused, DNS, TLS ...) for your log.

Messages are not queued while the socket is down: Send() returns false until it is Open again.

With m_bAutoReconnect off, a lost connection leaves the socket Closed for good.

Pitfalls

  • Unload closes. When your plugin unloads, its sockets are closed (code 1001, going away) and freed, and no callback runs anymore. Do not call a socket you still hold after that.
  • Copy message data. data in OnWebSocketMessage lives only for the call. In SourcePawn message is yours, but a binary message may contain zeros: use length, not the string length.
  • The world moves on. As with HTTP, carry SteamIDs or slots in your messages and resolve players when a message arrives, never pointers.
  • Callbacks run while the server hibernates, like HTTP's. Do not assume a map or players are there.

Reference

On this page