WebSocketServer

Description

Supported Script Types:

  • Server Entity Scripts
  • Assignment Client Scripts
Manages WebSockets in server entity and assignment client scripts.

Create using new WebSocketServer(...).

Properties

Name Type Summary
url string

The URL that the server is listening on. Read-only.

port number

The port that the server is listening on. Read-only.

listening boolean

true if the server is listening for incoming connections, false if it isn't. Read-only.

Constructor
new WebSocketServer( )

Examples

Echo a message back to sender.

// Server entity script. Echoes received message back to sender.
(function () {
    print("Create WebSocketServer");
    var webSocketServer = new WebSocketServer();
    print("Server url:", webSocketServer.url);

    function onNewConnection(webSocket) {
        print("New connection");

        webSocket.onmessage = function (message) {
            print("Message received:", message.data);

            var returnMessage = message.data + " back!";
            print("Echo a message back:", returnMessage);
            webSocket.send(message.data + " back!");
        };
    }

    webSocketServer.newConnection.connect(onNewConnection);
})
// Interface script. Bounces message off server entity script.
// Use the server URL reported by the server entity script.
var WEBSOCKET_PING_URL = "ws://127.0.0.1:nnnnn";
var TEST_MESSAGE = "Hello";

print("Create WebSocket");
var webSocket = new WebSocket(WEBSOCKET_PING_URL);

webSocket.onmessage = function(data) {
    print("Message received:", data.data);
};

webSocket.onopen = function() {
    print("WebSocket opened");
    print("Send test message:", TEST_MESSAGE);
    webSocket.send(TEST_MESSAGE);
};

Methods

Name Return Value Summary
close None

Closes all connections and closes the WebSocketServer.

Signals

Name Summary
newConnection

Triggered when there is a new connection.

Method Details

(static) close( )

Closes all connections and closes the WebSocketServer.

Signal Details

newConnection( webSocket )
Returns: Signal

Triggered when there is a new connection.

Parameters

Name Type Description
webSocket WebSocket

The WebSocket for the new connection.