- Notifications
You must be signed in to change notification settings - Fork90
How to create a Websocket server
The easiest way to handle Websocket requests is to use thewebsockets/ws module in a middleware plugin.
Install the
websocket/wsmodule.$ npm install --save-dev wsCreate a middleware plugin. Save the following example code as
websocket.js. This plugin delegates Websocket request handling to the websocket module by passing inlws.server. If a Websocket request comes in, it will be handled by this plugin else passed to the next middleware plugin in the stack.classWebsocket{middleware(config,lws){constWebSocket=require('ws')constwss=newWebSocket.Server({server:lws.server})wss.on('connection',socket=>{socket.on('message',message=>{console.log(`Received:${message}`)constreply="Wow, that's great"console.log(`Sending:${reply}`)socket.send(reply)})})}}exportdefaultWebsocket
Now we need a client to test our server. Save this as
index.html.<!DOCTYPE html><html><head><title>Websocket example</title></head><body><h1>Websocket example</h1><p><button>Send message</button></p><pre><code></code></pre><script>constsocket=newWebSocket('ws://localhost:8000')const$=document.querySelector.bind(document)functionsendMessage(msg){$('code').innerHTML+=`Sending:${msg}\n`socket.send(msg)}socket.addEventListener('open',()=>{sendMessage('Hello from the client')})socket.addEventListener('message',event=>{$('code').innerHTML+=`Received:${event.data}\n`})$('button').addEventListener('click',e=>{sendMessage('Client clicked the button')})</script></body></html>
Launch the server using our Websocket plugin pluslws-static to handle requests for static assets (e.g.
index.html).$ ws --stack websocket.js lws-staticListening on http://mba4.local:8000, http://127.0.0.1:8000, http://192.168.0.200:8000Finally, open your browser, navigate to
http://127.0.0.1:8000and click the button. On the client, you should see this output:Sending: Hello from the clientReceived: Wow, that's greatSending: Client clicked the buttonReceived: Wow, that's greatAnd the output from the server should look like this:
Received: Hello from the clientSending: Wow, that's greatReceived: Client clicked the buttonSending: Wow, that's great