The WebSocket API allows you to to maintain a continuous two-way connection between client and server. Messages can be sent and received on both ends.
This version has been modified to work with Typescript with minimal dependencies.
npm install
npm run build
npm start
open http://localhost:8080/
Try opening multiple browsers and looking at the logs on client and server. Here's what's happening:
- The client connects to
ws://localhost:8081/
via aWebSocket
- The client sends
{ message: 'Hello' }
to the server - The server sends
{ message: 'Gotcha '}
when a connection is established. - The server keeps track of all connections in
wss.clients
- Every three seconds the server broadcasts
{ message: 'Hello hello!' }
to all connections. - Connections can be closed by hitting the
Close
button or closing the window. - You can send
{ message: 'Hey' }
to the server by hittingSend Message
. - The server sends
{ message: 'Something changed' }
to all connections when a message is received.