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.
#include "source2mod/ISource2ModWebSockets.h"#include <source2mod/api> // the whole API, websockets.inc includedOpening a socket
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;
}Source2ModWebSocket g_feed;
public void OnPluginStart()
{
Source2ModHTTPHeaders headers = new Source2ModHTTPHeaders();
headers.Add("Authorization", "Bearer secret");
g_feed = new Source2ModWebSocket("wss://api.example.com/feed", OnFeedMessage,
OnFeedOpen, OnFeedClose, OnFeedError, 0, headers);
delete headers; // the socket copied them
}
public void OnFeedOpen(Source2ModWebSocket socket, bool reconnected, any data)
{
socket.Send("{\"type\":\"hello\",\"server\":\"eu-1\"}");
}
public void OnFeedMessage(Source2ModWebSocket socket, const char[] message, int length, bool binary, any data)
{
if (!binary)
HandleCommand(message);
}
public void OnFeedClose(Source2ModWebSocket socket, int code, const char[] reason, any data)
{
// Lost (1006) or closed by the server: it reconnects on its own.
}
public void OnFeedError(Source2ModWebSocket socket, const char[] error, any data)
{
Source2ModApi.Log("feed: %s", error);
}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
Source2ModWebSocketOptions | SourcePawn argument | Default | Meaning |
|---|---|---|---|
m_Headers | headers | none | Extra headers on the opening handshake (Authorization, cookies ...) |
m_bAutoReconnect | autoReconnect | true | Open the connection again when it is lost |
m_nPingIntervalSec | pingInterval | 30 | Seconds without traffic before a ping. After twice that with no traffic, the connection counts as lost. 0 turns pings off |
m_bVerifyPeer | verifyPeer | true | Check 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_nMaxMessageSize | none | 16 MB | A 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() | State | Connecting, Open or Closed |
GetUrl() | GetUrl(buffer, maxlen) | |
Destroy() | delete socket | Closes 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.
datainOnWebSocketMessagelives only for the call. In SourcePawnmessageis yours, but a binary message may contain zeros: uselength, 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
ISource2ModWebSocketsAPI reference- HTTP: one-off requests