Skip to content

Script Examples

Unreal Engine WebSocket API

This example talks to the Erizos Control plugin running inside Unreal Engine, whose control server listens on port 5000 by default. Erizos Studio itself does not expose a WebSocket API - the connection below goes straight from the user interface to the Unreal Engine machine.

Websocket example UI

Download ezUI File

WebSocketExample

This example provides a structured way to establish and manage a WebSocket connection and perform various operations using that connection, including request-response interactions and subscription to channels.

First, we need to establish a connection with the WebSocket. Then we created handlers for whether when a WebSocket connection is established successfully or not. We also created handlers for the Buttons that get/sets a data as well as the subscribing/unsubscribing from a channel.

Once the User Subscribed, he can then trigger notifications on the WebSocket clients.

Note

payload in this example is the name of a Text control in the example UI. It is unrelated to Api.page.payload.

Message format

Every message is a JSON string.

Request (user interface → Unreal Engine):

1
{ "method": "GET" | "POST", "url": "/api/…", "body": <any>, "id": <correlation id> }

The url must start with /api; the plugin strips that prefix and routes on the rest. A request whose path does not start with /api receives no answer at all. A request sent without an id is fire-and-forget - the plugin does not reply to it.

Response (Unreal Engine → user interface):

1
{ "id": "<the id from the request>", "status": 200, "headers": { … }, "body": <any> }

status is an HTTP status code: 200 OK, 403 not licensed or game not running, 404 unknown path, 500 internal error. Error bodies are { "error": "<description>" }. The id comes back as a string, which is why the sample below looks the pending request up with requests[obj.id].

Notification (Unreal Engine → every subscriber of a channel):

1
{ "channel": "MyChannel", "type": "<user defined>", "message": "<user defined>" }

A notification carries no id, which is how the sample tells the two apart.

Endpoints used in this example:

Method URL Description
GET /api/control Reads the current control state.
POST /api/control Sets the control state from the request body.
POST /api/notification/subscribe Subscribes this socket to { channel }.
POST /api/notification/unsubscribe Removes the subscription.

Unreal Engine Blueprint

BlueprintWebSocketExample SendTextWebSocketExample SendDataWebSocketExample

The Type/Message can be anything, determined entirely by the user. Both of them are represented as strings. The channel name is also free text, but it must be the same string in the Blueprint and in the subscribe call.

In the send data, we exposed our internal Data Json Serializer, which allows user to send data in the form of a JSON string, supporting various data structures.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
let ws: WebSocket = null;

connect.onClick = () => {
  if (ws && ws.readyState !== WebSocket.CLOSED) {
    // Detach the handlers first, so the old socket closing
    // does not report a disconnect for the new one
    ws.onopen = ws.onclose = ws.onerror = ws.onmessage = null;
    ws.close();
  }

  ws = null;
  ws = new WebSocket(`ws://${address.value.trim()}:5000`);
  ws.onopen = onConnected;
  ws.onclose = () => onDisconnected();
  ws.onerror = () => onDisconnected()
  ws.onmessage = onMessage;
}

function onConnected() {
  address.disabled = true;
  connect.disabled = true;
  status.title = 'Connected';
  status.type = 'success';
}

function onDisconnected(error?: string) {
  address.disabled = false;
  connect.disabled = false;
  status.title = error ?? 'Disconnected';
  status.type = 'error';

  // Nothing will answer these any more
  for (const id in requests) {
    requests[id].reject('WebSocket disconnected');
    delete requests[id];
  }
}

let message = 0;
type WSRequest = { resolve: (response: any) => void, reject: (error: string) => void };
const requests: Record<number, WSRequest> = {};

function onMessage(e: MessageEvent<string>) {
  console.log("GOT", e.data);
  const obj = JSON.parse(e.data);
  if (obj.id) {
    const pending = requests[obj.id];
    if (!pending)
      return;

    // Settle the request and drop it, so the map does not grow forever
    delete requests[obj.id];

    if (obj.status !== 200)
      return pending.reject(`Failed to process WS request, error: ${obj.status}`);

    pending.resolve(obj.body);
  }
  if (obj.channel) {
    switch (obj.type) {
      case 'Data':
        Alert.info('UE Sent JSON Data');
        payload.value = obj.message;
        const json = JSON.parse(obj.message);
        console.log('GOT Json Data', json)
        break;

      case 'Message':
        Alert.info(`UE Sent: ${obj.message}`);
        break;
    }
  }
}

function wsRequest(method: 'GET' | 'POST', url: string, body?: any): Promise<string> {
  if (ws?.readyState !== WebSocket.OPEN)
    return Promise.reject('WebSocket is not connected');

  return new Promise((resolve, reject) => {
    const id = message++;
    requests[id] = { resolve, reject };
    ws.send(JSON.stringify({ method, url, body, id }));
  })
}

btnGet.onClick = async () => {
  try {
    const res = await wsRequest('GET', '/api/control');
    payload.value = JSON.stringify(res, null, 2);
  } catch (error) {
    console.log('Failed to Get Control Data', error)
  }
}

btnSet.onClick = async () => {
  try {
    await wsRequest('POST', '/api/control', JSON.parse(payload.value));
  } catch (error) {
    console.log('Failed to Set Control Data', error);
  }
}

btnSubscribe.onClick = async () => {
  try {
    await wsRequest('POST', '/api/notification/subscribe', { channel: 'MyChannel' });
  } catch (error) {
    console.log('Failed to Set Control Data', error);
  }
}

btnUnsubscribe.onClick = async () => {
  try {
    await wsRequest('POST', '/api/notification/unsubscribe', { channel: 'MyChannel' });
  } catch (error) {
    console.log('Failed to Set Control Data', error);
  }
}

Tip

Alert is the built-in message helper. Alert.info(text, duration?) and its success, warning, error and loading variants show a message in the Studio window, and Alert.destroy(id) removes one. See IAlertService.