fastify-ws
WebSocket support for Fastify built on the blazing fast ws and uws libraries.
Example
In server.js
:
'use strict'
const fastify = require('fastify')()
fastify.register(require('fastify-ws'), {
pingInterval: 10000,
wsLibrary: 'uws'
})
fastify.ready(err => {
if (err) throw err
fastify.wsServer
.on('connection', ws => {
ws.on('message', msg => ws.send(msg))
})
})
fastify.listen(34567)
Then run node server.js
and navigate to http://localhost:34567
in your browser. In the browser's JavaScript console, open a client-side WebSocket connection:
const host = location.origin.replace(/^http/, 'ws')
const ws = new WebSocket(host)
ws.onmessage = msg => console.log(msg.data)
Then, still in the browser console, send some messages to the server and watch as they're echoed back to you:
ws.send('WebSockets are awesome!')
Notes
If you choose to use uws
as your WebSocket library, ensure that you have configured your system properly and understand that the API is a slightly reduced subset of ws
's.
TODO
License
Licensed under MIT.