How to use the ws.prototype function in ws

To help you get started, we’ve selected a few ws examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sebpiq / rhizome / test / helpers-backend.js View on Github external
, rimraf = require('rimraf')
  , oscServer = require('../lib/osc/Server')
  , oscTransport = require('../lib/osc/transport')
  , connections = require('../lib/connections')
  , coreServer = require('../lib/core/server')
  , coreMessages = require('../lib/core/messages')
  , ValidationError = require('../lib/core/errors').ValidationError
  , utils = require('../lib/core/utils')
  , helpersEverywhere = require('./helpers-everywhere')
_.extend(exports, helpersEverywhere)

// The directory we use for storing persisted data in tests
var testDbDir = exports.testDbDir = '/tmp/rhizome-test-db'

// For testing : we need to add standard `removeEventListener` method cause `ws` doesn't implement it.
WebSocket.prototype.removeEventListener = function(name, cb) {
  var handlerList = this._events[name]
  handlerList = _.isFunction(handlerList) ? [handlerList] : handlerList
  this._events[name] = _.reject(handlerList, (other) => other._listener === cb)
}

// Helper to create dummy web clients. Callack is called only when sockets all opened.
exports.dummyWebClients = function(wsServer, clients, done) {
  var countBefore = wsServer._wsServer.clients.length 
    , url, socket, sockets = []
  async.series(clients.map((client) => {
    return (next) => {
      _.defaults(client, { query: {} })
      client.query.dummies = ''
      url = 'ws://localhost:' + client.port + '/?' + querystring.stringify(client.query)
      socket = new WebSocket(url)
      _dummyWebClients.push(socket)
github sebpiq / rhizome / lib / websockets / Client.js View on Github external
Client.isSupported = function() {
  // For tests
  if (Client._isNotSupported) return false
  // Test 'websocketsbinary' copied from Modernizr source code :
  // https://github.com/Modernizr/Modernizr/blob/master/feature-detects/websockets/binary.js 
  if (Client._isBrowser) { 
    var protocol = 'https:' == location.protocol ? 'wss' : 'ws',
    protoBin

    if ('WebSocket' in window) {
      if (protoBin = 'binaryType' in WebSocket.prototype) {
        return protoBin
      }
      try {
        return !!(new WebSocket(protocol + '://.').binaryType)
      } catch (e) {}
    }

    return false 
  } else return true
}
github assaf / zombie / src / document.js View on Github external
window.WebSocket = function(url, protocol) {
    url = URL.resolve(document.URL, url);
    const origin = `${window.location.protocol}//${window.location.host}`;
    const ws = new WebSocket(url, { origin, protocol });

    // The < 1.x implementations of ws used to allows 'buffer' to be defined
    // as the binary type in node environments. Now, the supported type is
    // 'nodebuffer'. Version of engine.io-client <= 1.6.12 use the 'buffer'
    // type and this is a shim to allow that to keep working unti that version
    // of engine.io-client does not need to be supported anymore
    const origProperty = Object.getOwnPropertyDescriptor(WebSocket.prototype, 'binaryType');
    Object.defineProperty(ws, 'binaryType', {
      get: function get() {
        return origProperty.get.call(this);
      },
      set: function set(type) {
        if (type === 'buffer')
          type = 'nodebuffer';
        return origProperty.set.call(this, type);
      }
    });
    window._allWebSockets.push(ws);
    return ws;
  };
github olebedev / swarm / lib / swarm.js View on Github external
var swarm = (typeof(module)!=='undefined'&&module.exports) || {};
swarm.Peer = Peer;
swarm.Pipe = Pipe;
swarm.ID = ID;
swarm.Spec = Spec;
swarm.Plumber = Plumber;

if (typeof(module)!=='undefined') {
    WebSocket = require('ws');
    crypto = require('crypto');
}

if (typeof(WebSocket)!=='undefined') 
    Plumber.schemes['ws'] = WebSocket;

WebSocket._p = WebSocket.prototype;
if (!WebSocket._p.on)
    WebSocket._p.on = WebSocket._p.addEventListener;
if (!WebSocket.off)
    WebSocket._p.off = WebSocket._p.removeEventListener;

/*   Pain points
 *   * base refac
 *   * basic acl/security (by hexghost)
 *   * * * * 
 *
 * */
    /*function expectedSecret (id) {
        var hash = crypto.createHash('sha1');
        hash.update(id.toString());
        hash.update(self.host.masterSecret);
        return hash.digest('base64');
github OgarProject / Ogar / src / GameServer.js View on Github external
players++;
    });
    var s = {
        'current_players': this.clients.length,
        'alive': players,
        'spectators': this.clients.length - players,
        'max_players': this.config.serverMaxConnections,
        'gamemode': this.gameMode.name,
        'uptime': Math.round((new Date().getTime() - this.startTime) / 1000 / 60) + " m",
        'start_time': this.startTime
    };
    this.stats = JSON.stringify(s);
};

// Custom prototype functions
WebSocket.prototype.sendPacket = function(packet) {
    function getBuf(data) {
        var array = new Uint8Array(data.buffer || data);
        var l = data.byteLength || data.length;
        var o = data.byteOffset || 0;
        var buffer = new Buffer(l);

        for (var i = 0; i < l; i++) {
            buffer[i] = array[o + i];
        }

        return buffer;
    }

    //if (this.readyState == WebSocket.OPEN && (this._socket.bufferSize == 0) && packet.build) {
    if (this.readyState == WebSocket.OPEN && packet.build) {
        var buf = packet.build();
github nicktogo / coeditor / server / server.js View on Github external
function broadcastMsg(msg, ws) {
  let sockets = allSessions[ws.sessionId].wss;
  sockets.forEach( (socket) => {
    if (socket.readyState === WebSocket.OPEN && (socket.getId() !== ws.getId())) {
      console.log('Broadcasting msg to ' + socket.clientId + '\n');
      console.log(msg);
      console.log('\n');
      setTimeout( () => {
        socket.send(msg);
      }, 0);
    }
  });
}

WebSocket.prototype.createOrJoinSession = function(data) {
  let sessionId = data.sessionId;
  let clientId  = data.clientId;
  this.sessionId = sessionId;
  this.clientId  = clientId;
  if (typeof allSessions[sessionId] === 'undefined') {
    let session = {};
    session.wss = [];
    session.tabs = [];
    session.cursors = {};
    allSessions[sessionId] = session;
  }
  allSessions[sessionId].wss.push(this);
  console.log('Session ' + sessionId + ' adds ' + clientId + '\n');
};

WebSocket.prototype.getId = function() {
github bigbluebutton / bigbluebutton / labs / bbb-webrtc-sfu / lib / websocket.js View on Github external
/*
 * Simple wrapper around the ws library
 *
 */

var ws = require('ws');

ws.prototype.sendMessage = function(json) {

  return this.send(JSON.stringify(json), function(error) {
    if(error)
      console.log(' [server] Websocket error "' + error + '" on message "' + json.id + '"');
  });

};


module.exports = ws;
github nicktogo / coeditor / server / server.js View on Github external
let sessionId = data.sessionId;
  let clientId  = data.clientId;
  this.sessionId = sessionId;
  this.clientId  = clientId;
  if (typeof allSessions[sessionId] === 'undefined') {
    let session = {};
    session.wss = [];
    session.tabs = [];
    session.cursors = {};
    allSessions[sessionId] = session;
  }
  allSessions[sessionId].wss.push(this);
  console.log('Session ' + sessionId + ' adds ' + clientId + '\n');
};

WebSocket.prototype.getId = function() {
  return this.upgradeReq.headers['sec-websocket-key'];
};
github musiqpad / mqp-server / socketserver / socketserver.js View on Github external
const updateNotifier = require('update-notifier');
const fs = require('fs-extra');
const nconf = require('nconf');
const crypto = require('crypto');

//Files
const DB = require("./database");
const Room = require('./room');
const Mailer = require('./mail/mailer');
const YT = require('./YT');
const Roles = require('./role');
const log = new (require('basic-logger'))({showTimestamp: true, prefix: "SocketServer"});
const WebSocketServer = ws.Server;


ws.prototype.sendJSON = function(obj){
	try {
		this.send( JSON.stringify( obj ) );
	} catch (e){}
};

Date.prototype.addMinutes = function(m) {
   this.setTime(this.getTime() + (m*60*1000));
   return this;
};

Date.prototype.addHours = function(h) {
   this.setTime(this.getTime() + (h*60*60*1000));
   return this;
};

Date.prototype.addDays = function(days){
github christian-raedel / nightlife-rabbit / lib / session.js View on Github external
.then(function (message) {
        logger.debug('trying to send message', message);
        WebSocket.prototype.send.call(self.socket, message, function () {
            logger.debug('%s message sent', type, message);
        });
    })
    .catch(function (err) {

ws

Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js

MIT
Latest version published 6 months ago

Package Health Score

89 / 100
Full package analysis