Example: Hello World (Express)
Setup workspace
mkdir ./rxws-hello-world && cd ./rxws-hello-world
npm init -y
npm i --save express socket.io rxjs @buccaneer/rxws
touch startServer.js startClient.jsmkdir ./rxws-hello-world && cd ./rxws-hello-world
yarn init -y
yarn add express socket.io rxjs @buccaneer/rxws
touch startServer.js startClient.jsCreate a simple WebSocket server
// startServer.js
import express from 'express'; // eslint-disable-line import/no-extraneous-dependencies
import http from 'http';
import socketio from 'socket.io'; // eslint-disable-line import/no-extraneous-dependencies
// setup a basic WebSocket server using socket.io
function startServer(port = process.env.PORT || 3002) {
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Emit welcome message on connection
io.on('connection', (socket) => {
// Use socket to communicate with this particular client only, sending it it's own id
socket.emit('welcome', { message: 'Ahoy matey!', id: socket.id });
socket.on('fromclient', console.log);
// Send a message every 3 seconds:
setInterval(
() => socket.emit(
'message',
{ text: 'Aye aye!', sentAt: new Date().toJSON() }
),
3000
);
});
server.listen(port, () => console.log(`⛵ Listening on ${port}`));
}
startServer();Create an rxws client
rxws clientLast updated