Skip to main content

Web Sockets

In order to create your Web Sockets, add a sockets folder to your less folder.

mkdir -p less/sockets

Less allows you to create several Web Sockets in the same project. In order to create a new socket, add it to the sockets folder.

For example, to create a demo socket add a folder named demo to less/sockets:

mkdir less/sockets/demo

Handle Client Connections

When a client connects or disconnects from your socket, the respective connect or disconnect function will be called, providing the client's connection_id.

In order to handle the connect & disconnect events, add your connect and disconnect handlers to your socket.

Client Connected

mkdir less/sockets/demo/connect
touch less/sockets/demo/connect/index.js
less/sockets/demo/connect/index.js
exports.process = async ({ connection_id }) => {
console.log('Client connected: ' + connection_id);
// Save the client's connection_id so you can send messages to them later.
};

Deploy and test your Web Socket connect handler

npx @chuva.io/less-cli deploy my-less-project
Connect to your socket

Here's an example of connecting using wscat:

wscat -c wss://[PROJECT-NAME]-[SOCKET-NAME].ws.eu-0.4dd0b49.less.chuva.cv
View connection logs
npx @chuva.io/less-cli log --project my-less-project --path sockets/demo/connect
Less Logs Documentation

Read the Less logs documentation to learn more.


Don't forget to save your connection_id.

Save your connection_id so you can use it later.

Here's an example of how you can save your connection_id using Less's built in Key-Value Store:

less/sockets/demo/connect/index.js
// Import the Key-Value Store from Less.
const { kvs } = require('@chuva.io/less');

exports.process = async ({ connection_id }) => {
console.log('Client connected: ' + connection_id);

// Save your socket connection_id
await kvs.set('DEMO_SOCKET_CONNECTION_ID', connection_id);
};

Client Disconnected

mkdir less/sockets/demo/disconnect
touch less/sockets/demo/disconnect/index.js
less/sockets/demo/disconnect/index.js
exports.process = async ({ connection_id }) => {
console.log('Client disconnected: ' + connection_id);
// Delete the connection_id from your database.
};

Send Messages

We can use the connection_id obtained in the socket connect handler in order to send messages to connected clients.

Import sockets from @chuva.io/less to send messages to your socket's clients.

const { sockets } = require('@chuva.io/less');

This allows you to send messages to an array of client connection IDs for the designated socket.

Here's an example of publishing a message to clients connected to a demo socket:

const { sockets } = require('@chuva.io/less');

await sockets.demo.publish(
message,
[connection_id_1, connection_id_2]
);

Let's create a POST /hello route that will send messages to a connected client. We will retrieve the client connection_id that we saved in the socket connect handler from the Key-Value Store.

touch less/apis/demo/hello/post.js
less/apis/demo/hello/post.js
const { sockets, kvs } = require('@chuva.io/less');

exports.process = async (request, response) => {
// Get the connection_id from kvs.
const CONNECTION_ID = await kvs.get('DEMO_SOCKET_CONNECTION_ID');

// Publish a message to the specified connections to the `demo` socket.
await sockets.demo.publish(
'Hello from POST /hello',
[CONNECTION_ID]
);

response.statusCode = 204;
return response;
};
Less REST API Documentation

Read the Less REST API documentation to learn more.

You can now deploy and call your POST /hello route and confirm that your client is receiving the message:

  1. Deploy your changes.
npx @chuva.io/less-cli deploy my-less-project
  1. Connect to your socket.
wscat -c wss://[PROJECT-NAME]-[SOCKET-NAME].ws.eu-0.4dd0b49.less.chuva.cv
  1. In a separate terminal window POST to /routes.
curl -X POST [BASE_URL]/hello
  1. Go back to your previous terminal window and confirm the message was received.

Create Channels

Channels allow clients to send messages to your socket. In order to create a channel for your socket, simply create a channel processor in your socket's folder.

Create a my_channel channel in your demo socket:

mkdir less/sockets/demo/my_channel
touch less/sockets/demo/my_channel/index.js
less/sockets/demo/my_channel/index.js
exports.process = async ({ data, connection_id }) => {
console.log(`Received message from: ${connection_id}`);
console.log(`Message: ${data}`);
};

You can now deploy your changes:

npx @chuva.io/less-cli deploy my-less-project

The client can send messages to the server by sending a JSON payload with the channel name and the data to be sent.

Here's an example of sending messages from a client to the server using wscat:

wscat -c wss://[PROJECT-NAME]-[SOCKET-NAME].ws.eu-0.4dd0b49.less.chuva.cv
Connected (press CTRL+C to quit)
> { "channel": "my_channel", "data": "Hello from a socket client." }

Check your socket channel logs:

npx @chuva.io/less-cli log --project my-less-project --path sockets/demo/my_channel
Less Logs Documentation

Read the Less logs documentation to learn more.


Send a message back to the client to test:

less/sockets/demo/my_channel/index.js
const { sockets } = require('@chuva.io/less');

exports.process = async ({ data, connection_id }) => {
console.log(`Received message from: ${connection_id}`);
console.log(`Message: ${data}`);

// Publish a message to the specified connections to the `demo` socket.
const message = `You said: "${JSON.stringify(data)}"`;
await sockets.demo.publish(message, [connection_id]);
};

Deploy and test again:

npx @chuva.io/less-cli deploy my-less-project
wscat -c wss://[PROJECT-NAME]-[SOCKET-NAME].ws.eu-0.4dd0b49.less.chuva.cv
Connected (press CTRL+C to quit)
> { "channel": "my_channel", "data": "Hello from a socket client." }
< "You said: \"Hello from a socket client.\""