npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ws-events-and-middlewares

v1.1.1

Published

ws module wrapper to provide events

Downloads

29

Readme

ws-events-and-middlewares

Esta libreria esta concebida como un wrapper del modulo ws de node. Seguro que muchos de vosotros cuando usásteis la tecnología de websocket por primera vez lo hicísteis a traves de la maravillosa libreria de Socket.io

El problema de esta libreria es la integración con React Native y Socket.io-client (version portable del cliente de Socket.io) ya que Socket.io no ha dado soporte propio para React Native.

Cuando te planteas migrar todo el código hecho en Socket.io a la libreria ws 'nativa' te encuentras con el dilema de la gestión del eventos y la escasa versatilidad que te ofrece tener un único evento 'message' para comunicarte con tus cliente.

Veamos un ejemplo del uso de ws sin la libreria de este repositorio:

Construyendo un servidor websockets con ws

// Importamos la libreria de ws
const WebSocket = require('ws')

// Iniciamos un servidor websocket en el puerto 3000
const wss = new WebSocket.Server({ port: 3000 })

// Escuchamos el evento connection para detectar cuando se conecta un cliente
wss.on('connection', function connection(ws) {

  // Escuchamos el evento message para detectar cuando nos envian un mensaje (no podemos cambiar el nombre del evento)
  ws.on('message', function (message) {
    console.log('Mensaje recibido: %s', message)
  })
 
  // Enviamos un mensaje de Ready para indicar al cliente que estamos listos para comunicarnos con el
  ws.send('ready')
})

Contruyendo la conexión desde el cliente


// Importamos la libreria de ws
const WebSocket = require('ws');
 
// Nos conectamos a nuestro servidor websocket en el puerto 3000
const ws = new WebSocket('ws://www.host.com:3000/path');

// Cuando la conexión este lista y abierta
ws.on('open', function open() {
  ws.send('Hola servidor!') // Enviamos un mensaje al servidor
})

// Cuando recibamos un mensaje del servidor
ws.on('message', function incoming(data) {
  console.log(data) // Imprimimos lo que el servidor nos este enviando
})

El problema que se nos presenta aquí en oposición a la libreria de Socket.io es que no tenemos forma de modificar el 'tipo' de mensaje que enviamos y estamos obligados a tomar medidas del tipo:

{
  type: 'GET_CONNECTED_USERS', // Tipo de mensaje que enviamos
  payload: {
    bar: 'foo'
  }
}

Por otra parte tampoco tenemos gestión de callbacks y nos vemos obligado a esperar recibir un mensaje de respuesta. Como tampoco tenemos gestión para middleware.

Para solucionar estos problemas podemos implementar la libreria ligera de este repositorio:

Instalando ws-events-and-middlewares

  npm install ws-events-and-middlewares --save

o

  yarn install ws-events-and-middlewares --save

Construyendo el servidor con eventos

Construyendo el cliente

Construyendo el servidor con eventos y middlewares

Construyendo el servidor con eventos, middlewares y salas de broadcast

TODO list