Code Monkey home page Code Monkey logo

fastify-ws's Introduction

fastify-ws

Build Status npm version

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'), {
  library: 'uws' // Use the uws library instead of the default ws library
})

fastify.ready(err => {
  if (err) throw err

  fastify.ws
    .on('connection', socket => {
      socket.on('message', msg => socket.send(msg)) // Creates an echo server
    })
})

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!')
// => undefined
// LOG: 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.

License

Licensed under MIT.

fastify-ws's People

Contributors

gj avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.