WebSockets and Rooms
Achieve works easily with other Node.js packages. The Startup tab shows
how ws adds WebSocket support to the Achieve HTTP server.
To start the WebSocket demonstration, open a terminal in the extracted
achieve_examples directory and enter:
npm run start:websockets
Refresh this browser page after starting the WebSocket-enabled server to establish the WebSocket connections.
Another package, achieve_rooms, organizes WebSocket connections into groups, much like chat rooms. The three clients below initially join the same room and can exchange messages with the other clients in that room.
Try it
All three clients initially join room1. Send a message from any client and watch the same message appear in the other clients.
Now use the Change rooms field in one client to move it to room2. Send another message. The client in room2 is now isolated from the clients still in room1.
Move a second client to room2 and try again. The two clients in room2 can now exchange messages with each other, while the remaining client stays in room1.
HTTPS and WSS
Click the Startup tab to see the HTTP startup code used by this example.
To use HTTPS/WSS, add:
import fs from 'node:fs';
const options = {
key: fs.readFileSync('[path]/privkey.pem'),
ca: fs.readFileSync('[path]/chain.pem'),
cert: fs.readFileSync('[path]/fullchain.pem'),
httpsPort: 8990 // or whatever port you choose
};
Then replace:
const server = achieve.listen(8989);
with:
const server = achieve.slisten(options); // HTTPS/WSS
The rest of the startup code remains the same.