There are two ways to send a WebSocket message to a client:
- Via the
connection.send()
method on theconnection
object passed to your WebSocket endpoint’son_open()
,on_message()
, andon_close()
event handlers. - Via the
websockets()
function available as a named export from@joystick.js/node
.
Example Usage
Sending Messages via the Connection Object
/index.server.js
import joystick from '@joystick.js/node';
joystick.app({
websockets: {
example_endpoint: {
on_open: (connection = {}) => {
connection.send(JSON.stringify({ message: 'Hello from the server!' }));
},
on_message: (message = {}, connection = {}) => {
connection.send(JSON.stringify({ message: 'Hello from the server!' }));
},
on_close: (code = 0, reason = '', connection = {}) => {
connection.send(JSON.stringify({ message: 'Hello from the server!' }));
},
},
},
routes: { ... },
});
When sending messages using connection.send()
, ensure the message is stringified as JSON (JSON.stringify()
) because Joystick’s client-side WebSocket connection expects messages to be JSON-formatted.
Sending Messages via the websockets() Function
/index.server.js
import joystick, { websockets } from '@joystick.js/node';
joystick.app({
websockets: {
example_endpoint: {
on_open: (connection = {}) => {
websockets('example_endpoint').send({ message: 'Hello from the server!' });
},
on_message: (message = {}, connection = {}) => {
websockets('example_endpoint').send({ message: 'Hello from the server!' });
},
on_close: (code = 0, reason = '', connection = {}) => {
websockets('example_endpoint').send({ message: 'Hello from the server!' });
},
},
},
routes: { ... },
});
The websockets()
function returns an object with a .send()
method that automatically stringifies your message, allowing you to pass a plain JavaScript object.
Filtering Messages for Specific Clients
Sending a Message to a Specific ID
websockets('example_endpoint').send(
{ message: 'Hello from the server!' },
'some_unique_id_abc123'
);
Here, the some_unique_id_abc123
string filters the message to only clients who passed the same ID in their WebSocket connection’s query.id
.
API
Definition
websockets(websocket_name: string) => {
send: (message: object, channel_id: string) => void
}
Parameters
- websocket_name string required
- The name of the WebSocket server to target.
Returns
{
send: (message: object, channel_id: string) => void
}
- send function required
-
A function that sends a message to clients connected to the specified WebSocket server. Accepts a
message
object (required) and an optionalchannel_id
string to filter recipients.