Websockets allow real time “pushing” of data between the backend of your app and the frontend of your app.
Here’s an example of using Express with Websockets to create a websocket connection between the server.js
and the consuming index.html
and assets/client.js
:
Responsibilities per file:
server.js
- creates the websocket connection && serves theindex.html
file on the root pathassets/script.js
- creates the client side websocket instance and connects to the server instanceindex.html
- duh
Chat Example with Express, Websockets & React
This example is slightly more advanced. In addition to Express & Websockets it includes the use of React & React useEffect
and useState
hooks for state management:
On the backend, the server.js
will broadcast messages to all connected clients. This is possible with the wss.clients.forEach(...)
statement. Very cool.
Responsibilities per file:
server.js
- creates the websocket connection && serves theindex.html
file on the root pathapp/components/Chat.jsx
- creates the client side websocket instance and connects to the server instanceindex.html
- duh
I gave a presentation on this for the Cleveland React meetup group. Here’s the slides if you’d like to run through them to learn more about WebSockets and how they differ from normal API calls: