Socket.io is the simples way to work with WebSockets in Node.js
This example shows how to setup socket.io inside a Express server and together with a Remix app and how to connect from the browser.
To run this example, run npm run dev
.
Note: The code here needs the Express adapter and because of that it needs Node.js. This is only deployable to platforms supporting a persistent running process (unlike Serverless platforms).
Open this example on CodeSandbox:
This example uses the Express adapter to setup the HTTP server.
Then it attaches socket.io to it and listens for a few basic events.
Client-side, it imports io
from socket.io-client
and uses it to connect to the WebSocket server on the root component.
It stores the socket instance in a React context and make it available for the whole app.
In the routes/_index
file, it accesses the socket instance to listen for more events and renders a button which sends a message to the server on each click.