In App chat bot with Web Sockets

Hi Friends

I want to add a “chat bot” to my app and suspect I need to use websockets for it to work properly.

Can I do this with normal JS/TS in the runtime, or will I need to implement this via HTML Bridge / custom app package?

@forumfred That is an excellent question. A basic investigation seems to suggest that there should be no problems connecting with WebSockets directly from the runtime.

Here is a very basic example that was used for the test by connecting to a local websocket server. The local server starts sending “Hello!” messages every second once a connection has been established.

let webSocket: WebSocket = null

async function wsError(error) {
    console.error("WebSocket error", error)
}

async function wsMessage(message: MessageEvent<any>) {
    console.log("WebSocket Message", message)
}

async function wsOpen() {
    console.log("WebSocket opened");
}

async function wsClose() {
    console.log("WebSocket closed");
}

async function createConnection(url: string) {
    webSocket = new WebSocket(url);
    
    webSocket.onclose = wsClose;
    webSocket.onerror = wsError;
    webSocket.onmessage = wsMessage;
    webSocket.onopen = wsOpen
}

async function closeConnection() {
    webSocket.close();
}

Output:

Now your mileage may vary depending on your exact implementation, but fundamentally it seems to work as expected.