How to use nodejs-websocket - 10 common examples

To help you get started, we’ve selected a few nodejs-websocket 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 IntelOpenDesign / MakerNode / test-server.js View on Github external
// change state randomly to simulate other users and hardware
function update() {
    _und.each(all_pins, function(id) {
        if (!msg.pins[id].is_input)
            return;
        if (msg.pins[id].is_analog) {
            msg.pins[id].value = Math.random();
        } else {
            msg.pins[id].value = Math.random() < 0.5 ? 0 : 1;
        }
    });
}

setInterval(update, 6000);

var server = ws.createServer(function(conn){

    N_CLIENTS += 1;
    console.log('new connection, N_CLIENTS', N_CLIENTS);

    var broadcast_interval_id = setInterval(function() {
        msg.count += 1;
        msg.message_ids_processed = _und.keys(messages_dict);
        conn.sendText(JSON.stringify(msg));

        _und.each(_und.keys(messages_dict), function(id) {
            messages_dict[id] += 1;
        });
        var message_ids_to_delete = _und.filter(_und.keys(messages_dict),
            function(id) { return messages_dict[id] >= N_CLIENTS * 2; });
        _und.each(message_ids_to_delete, function(id) {
            delete messages_dict[id];
github angular / zone.js / test / ws-server.js View on Github external
/**
 * @license
 * Copyright Google Inc. All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

const ws = require('nodejs-websocket');

// simple echo server
const server = ws.createServer(function (conn) {
  conn.on('text', function (str) {
    if (str === 'close') {
      server.close();
      return;
    }
    conn.sendText(str.toString());
  });
}).listen(8001);
github progrium / duplex / javascript / demo / server.js View on Github external
// SETUP RPC
var rpc = new duplex.RPC(duplex.JSON)
rpc.register("echo", function(ch) {
  ch.onrecv = function(obj) {
    ch.send(obj)
  }
})
rpc.register("doMsgbox", function(ch) {
  ch.onrecv = function(text) {
    ch.call("msgbox", text)
  }
})

// WEBSOCKET SERVER
var server = ws.createServer(function (conn) {
  rpc.accept(duplex.wrap["nodejs-websocket"](conn))
}).listen(8001)
console.log("WS on 8001...")
github devfacet / natsboard / lib / server.js View on Github external
path    = require('path');

var ARGS         = utilex.args(),
    APP_PATH     = path.resolve(path.join(__dirname, '..')),
    NODE_PORT    = process.env.NODE_PORT    || ARGS['port']         || '3000',
    NODE_PORTWS  = process.env.NODE_PORTWS  || ARGS['port-ws']      || parseInt(NODE_PORT)+1,
    NATS_MON_URL = process.env.NATS_MON_URL || ARGS['nats-mon-url'] || 'http://localhost:8222';

// Handle errors - for preventing websocket issues
process.on('uncaughtException', function (err) {
  console.error(err);
});

// Init server
var app = express(),
    ws  = ws.createServer();

app.set('NODE_PORT',    NODE_PORT);    // server port
app.set('NODE_PORTWS',  NODE_PORTWS);  // websocket port
app.set('NATS_MON_URL', NATS_MON_URL); // nats monitoring url
app.set('WS',           ws);           // websocket server

app.use(require('./metrics')(app));  // metrics
app.use(require('./routes')(app));   // routes
app.use(express.static(path.join(APP_PATH, 'public'))); // static file serving

// Start web server
app.listen(NODE_PORT);
console.log(util.format('Web server listening at %s', NODE_PORT));

// Start ws server
ws.listen(NODE_PORTWS);
github vcync / modV / mediaManager.js View on Github external
}
		});

	});
	callback();
}

/* Server */
var clients = [];

function update(conn) {
	console.log('Sending client profiles data');
	conn.send(JSON.stringify({type: 'update', payload: profiles}));
}

var server = ws.createServer(function(conn) {
	console.log('New client!');

	var clientIndex = clients.push(conn)-1;
	conn.clientIndex = clientIndex;

	conn.on('close', function() {
		clients.splice(clients.indexOf(conn), 1);
		//clients.splice(conn.clientIndex, 1);
	});

	conn.on('error', function(err) {
		console.error(err);
	});

	conn.on('text', function(msg) {
		var parsed = JSON.parse(msg);
github NERDDISCO / luminave / server-bin / core / WebSocketServer.js View on Github external
function WebSocketServer(param) {
    _classCallCheck(this, WebSocketServer);

    this.port = param.port || 1337;
    this.debug = param.debug || false;

    /**
     * Create a WebSocket server
     */
    this.server = ws.createServer(function (connection) {

      console.log('New connection');

      // Receive data
      connection.on('text', function (data) {
        if (this.debug) {
          console.log(data);
        }

        data = JSON.parse(data);

        if (this.debug) {
          console.log(JSON.stringify(data));
        }
      });
github NERDDISCO / luminave / src / core / WebSocketServer.js View on Github external
constructor(param) {
    this.port = param.port || 1337;
    this.debug = param.debug || false;

    /**
     * Create a WebSocket server
     */
    this.server = ws.createServer(function(connection) {

      console.log('New connection');

      // Receive data
      connection.on('text', function(data) {
        if (this.debug) {
          console.log(data);
        }

        data = JSON.parse(data);

        if (this.debug) {
          console.log(JSON.stringify(data));
        }

      });
github PRINTR3D / formide-client / src / utils / websocket / index.js View on Github external
init: function() {

		var self = this;

		// base websocket server to LCD display notifications and events
		var nativeSocketServer = ws.createServer(function (conn) {

			function forwardEvents(event, data) {
				data = data || {};
				data.device = "LOCAL";
				conn.sendText(JSON.stringify({
					channel: event,
					data:    data
				}));
			}

			conn.on("text", function (message) {
				try {
					var data = JSON.parse(message);
					if (data.channel === "authenticate") {
						authenticate(data.data.accessToken, function(err, accessToken) {
							if (err) console.log(err);
github UweGruenefeld / UnityNetworkModel / server / nodejs / server.js View on Github external
const COMPONENT_DELETE	= 'cd';

// Data storage
var model = {};
var ressources = {};
var clients = {};
var subscriptions = {};

//
// SERVER
//

// Server configuration
var config = require('./config.json');
var websocket = require('nodejs-websocket');
var server = websocket.createServer(function(connection)
{
	// Handle event for open connection
	onOpen(connection);

	// Handle event for closing connection
	connection.on('close', function()
	{
		onClose(connection)
	});

	// Handle event for incoming message
	connection.on("text", function(message)
	{
		onText(connection, message);
	});
});
github mdopp / simple-sonoff-server / sonoff.server.module.js View on Github external
// Register routes
    server.get('/', function (req, res) {
        log.log('REQ | %s | %s ', req.method, req.url);
        res.send('OK');
    });

    // ----------- sonoff server ------------------------
    // setup a server, that will respond to the SONOFF requests
    // this is the replacement for the SONOFF cloud!
    var wsOptions = {
        secure: true,
        key: config.server.privateKey,
        cert: config.server.certificate
    };

    const wsServer = ws.createServer(wsOptions, function (conn) {
        log.log("WS | Server is up %s:%s to %s:%s", config.server.IP, config.server.websocketPort, conn.socket.remoteAddress, conn.socket.remotePort);

        conn.on("text", function (str) {
            var data = JSON.parse(str);
            log.trace('REQ | WS | DEV | %s', JSON.stringify(data));
            res = {
                "error": 0,
                "deviceid": data.deviceid,
                "apikey": "111111111-1111-1111-1111-111111111111"
            };
            if (data.action) {
                switch (data.action) {
                    case 'date':
                        res.date = new Date().toISOString();
                        break;
                    case 'query':

nodejs-websocket

Basic server&client approach to websocket (text and binary frames)

MIT
Latest version published 6 years ago

Package Health Score

50 / 100
Full package analysis

Popular nodejs-websocket functions