Skip to content

Script Examples

WebSocket API

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.

Unreal Engine Blueprint

BlueprintWebSocketExample SendTextWebSocketExample SendDataWebSocketExample

The Type/Message can be anything, determined entirely by the user. Both of them are represented as strings.

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
let ws: WebSocket = null;

connect.onClick = () => {
  if (ws && ws.readyState !== WebSocket.CLOSED)
    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';
}

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;

    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);
  }
}