Giter Club home page Giter Club logo

cws's Introduction

ClusterWS/cWS Implementation

Modified version of uWebSockets

This module is modified version of the uWebSockets with some minor tweaks in C++ code and complete rewrite of JS code to TS. Original software is available in uWebSockets repository.

npm version

This repository is based on the uWebSockets therefore has two licence ClusterWS MIT and Alex Hultman ZLIB.

Big thanks to SirAnthony for ssl workaround (has been taken from SirAnthony's uWebSockets fork).

Please consider to support ClusterWS development:

Installation

npm i @clusterws/cws

Server example

// use WebSocketServer to create server
const { WebSocketServer } = require('@clusterws/cws');

// Create websocket server 
const server = new WebSocketServer({ port: 3000 }, () => {
    console.log('Server is running on port: ', 3000)
});

// Accept ws connections
server.on('connection', (socket, upgReq) => {
    // gives you remoteAddress info
    let address = socket._socket 
    // emitted when receive new message
    socket.on('message', (message) => { });

    // emitted when connection closes 
    socket.on('close', (code, reason) => { });

    // emitted on error
    socket.on('error', (err) => { });

    // emitted when pong comes back from the client connection
    socket.on('pong', () => { 
      // make sure to add below line (important to do not drop connections)
      socket.isAlive = true;
    });

    // emitted when get ping from the server (if you send)
    socket.on('ping', () => {})

    // this function accepts string or binary (node buffer)
    socket.send(message)

    // destroy connection
    socket.terminate()

    // close connection
    socket.close(code, reason)

    // to manually send ping to the client
    socket.ping()
});

server.on('error', (err, socket) => {
  // in some cases there is not socket param
  // handle http errors, TLS errors, ... 
})

// Start auto ping (second parameter is type of ping `false` is low level)
// use `false` most of the time except if you want to track ping pong on the client side 
// which does not have onping & onpong methods (like browser websocket)
// check Handle AutoLevelPing In Browser Example part below
// event if you use app level ping server onPong will be called
server.startAutoPing(20000, false)

// broadcast to all connected clients
// message: string | binary (node buffer)
// options?: { binary: true | false }
server.broadcast(message, options)

// destroy or close server
server.close(callback)

Client example

// Client part is pretty much the same as in server
// use WebSocket to create client
const { WebSocket } = require('@clusterws/cws');

const socket = new WebSocket('ws://url:port');

// emitted when websocket is connected
socket.on('open', () => {})

// emitted when receive new message
socket.on('message', (message) => { });

// emitted when error happens
socket.on('error', (err) => {})

// emitted on close websocket
socket.on('close', (code, reason) => {})

// emitted when get ping from the server (if you send)
socket.on('ping', () => {})

// emitted when get pong from the server (if you send)
socket.on('pong', () => {})

socket.ping() // manually send ping to the server

socket.send(msg) // send message to the server binary | string

socket.terminate() // destroy connection

socket.close(code, reason) // close connection

Replace EventEmitter

To replace custom event emitter you have to overwrite global cws parameter before importing @clusterws/cws ex:

// this code uses default node js event emitter
global.cws = {
  EventEmitter: require('events').EventEmitter
}

// import cws
const { WebSocket } = require('@clusterws/cws');

Handle AppLevelPing In Browser Example

This is just an example of handling app level ping pong from the client side which does not have onping and onpong methods available

Note if your clients have onping and onpong methods (or similar) do not send appLevel ping from the server as it requires more work.

socket.binaryType = 'arraybuffer' // Do not forget to set to `arraybuffer`
socket.onmessage = function (message) {
    if (typeof message.data !== 'string') {
        let buffer = new Uint8Array(message.data);
        if (buffer[0] === 57) {
            // output should be an array with one bit and [0] is === 65
            return socket.send(new Uint8Array(['A'.charCodeAt()]));
        }

        // process with your binary data
    }
    // process with your string data
}

cws's People

Contributors

goriunov avatar goriunovphl avatar iralph avatar rivertam avatar tmcgannon avatar

Watchers

 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.