Velo Websockets

Hello, I am building a project that lets my clients communicate through chat with their own customers / users. The messages go from the user’s chat, to my backend, and end up in my client’s inbox. Then my client can respond to these messages and so on… To implement this I figured out that I need to create a websocket from my backend, in order to keep these connections open. I installed both the ‘ws’ and ‘websocket’ npm packages, but the latter needs the http server object, which as far as I know I can’t acquire. When it comes to the ‘ws’ package, I managed to make it listen to connections with the following code, but I can’t connect to it from my client (Perhaps it uses a URL endpoint that I am not aware of). Note that I cannot use the Wix realtime-api because the connections will not come from my wix front-end. What am I doing wrong? Thank you all

import { WebSocketServer } from 'ws';

export function startWebSocketServer() {
    const wss = new WebSocketServer({ port: 8082 });

    wss.on('listening', () => {
        console.log(`WebSocket server listening on ${wss.address().port}`);
    });

    wss.on('connection', (socket) => {
        console.log('WebSocket connection opened');

        socket.on('message', (message) => {
            console.log(`Received message: ${message}`);

            // Echo the message back to the client
            socket.send(`Echo: ${message}`);
        });

        socket.on('close', (code, reason) => {
            console.log(`WebSocket connection closed: code=${code}, reason=${reason}`);
        });

        socket.send('Hello, client!');
    });

    wss.on('close', () => {
        console.log('WebSocket server closed');
    });
}
1 Like

Wix doesn’t support long running processes like web sockets so what’s going to happen here is the server will run for a short period of time and then terminate.

Besides wix-realtime the other option you have is wix-http-functions https://www.wix.com/velo/reference/wix-http-functions/introduction . This can be used to define REST endpoints that your site can respond to.