-
Notifications
You must be signed in to change notification settings - Fork 91
How to create a Websocket server
Lloyd Brookes edited this page Jun 17, 2019
·
4 revisions
The easiest way to handle Websocket requests is to use the websockets/ws module in a middleware plugin.
- Install the
websocket/ws
module.
$ npm install --save-dev ws
- Create 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.
class Websocket {
middleware (config, lws) {
const WebSocket = require('ws')
const wss = new WebSocket.Server({ server: lws.server })
wss.on('connection', socket => {
socket.on('message', message => {
console.log(`Received: ${message}`)
const reply = "Wow, that's great"
console.log(`Sending: ${reply}`)
socket.send(reply)
})
})
}
}
module.exports = Websocket
- 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>
const socket = new WebSocket('ws://localhost:8000')
const $ = document.querySelector.bind(document)
function sendMessage (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 plus lws-static to handle requests for static assets (e.g.
index.html
).
$ ws --stack websocket.js lws-static
Listening on http://mba4.local:8000, http://127.0.0.1:8000, http://192.168.0.200:8000
- Finally, open your browser and navigate to
http://127.0.0.1:8000
and click the button. On the client, you should see this output:
Sending: Hello from the client
Received: Wow, that's great
Sending: Client clicked the button
Received: Wow, that's great
And the output from the server should look like this:
Received: Hello from the client
Sending: Wow, that's great
Received: Client clicked the button
Sending: Wow, that's great