Coder Social home page Coder Social logo

websocket's Introduction

@idio/websocket

npm version

@idio/websocket Establishes WebSocket Connections Between Clients And The Server.

yarn add @idio/websocket
npm i @idio/websocket

Table Of Contents

API

The package is available by importing its default function:

import websocket from '@idio/websocket'

websocket(
  server: !http.Server,
  config=: !WebSocketConfig,
): !Object<string, sendMessage>

Sets up a listener for the UPGRADE event on the server, and stores all connected clients in the client list. When clients disconnect, they are removed from this list. The list is a hash object where each key is the accept key sent by the client, and values are the callback functions to send messages to those clients.

WebSocketConfig: Options for the web socket protocol communication.

Name Type Description Default
log boolean Whether to log on connect and disconnect. true
onMessage (clientID: string, message: string) => void The callback when a message is received from a client. -
onConnect (clientID: string) => void The callback when a client is connected. -

With the following client-side implementation:

/* eslint-env browser */
const ws = new WebSocket(`ws://${location.host}`, 'json')
setInterval(() => {
  if (ws.readyState == ws.OPEN) ws.send('')
}, 2000)

ws.addEventListener('message', async event => {
  const { message, event: e } = JSON.parse(event.data)
  console.log('Received %s:', e, message)
  window.WSstatus.innerText = message
  ws.send(navigator.userAgent)
})

the server can be setup to listen for connections.

/* yarn example/ */
import core, { render } from '@idio/idio'
import websocket from '@idio/websocket'

(async () => {
  const { url, server } = await core({
    static: {
      use: true,
      root: 'example/frontend',
    },
    index(ctx) {
      ctx.body = render(
        <html>
          <head>
            <title>Websocket Example</title>
          </head>
          <body>
            <h1>
              Hello World.
            </h1>
            Server says: <span id="WSstatus" />
            <script type="module" src="index.js"/>
          </body>
        </html>
        , { addDoctype: true })
    },
  })
  const clients = websocket(server, {
    onConnect(clientId) {
      clients[clientId]('handshake', 'welcome')
    },
    onMessage(clientId, message) {
      console.log('Client %s says: %s', clientId, message)
    },
  })
  console.log(url)
})()
http://localhost:5000
Client connected.
Client FIM/Jvt9Ldb1J0HCx5ye8g== says:
  Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0)
  AppleWebKit/537.36 (KHTML, like Gecko)
  Chrome/71.0.3578.98 Safari/537.36
Client disconnected.

sendMessage(
  event: string,
  message: *,
): void

  • event* string: The name of the event to send.
  • message* *: The data, that will be serialised in JSON.

Copyright

Art Deco © Art Deco™ for Idio 2020 Idio

WebSocket Node.JS implementation by Srushtika Neelakantam from Implementing a WebSocket server with Node.js

websocket's People

Contributors

zavr-1 avatar

Stargazers

 avatar

Watchers

 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.