Example #1
0
// a useful client for interacting with bbb-server as a client

var repl = require("repl");
var io = require("socket.io-client");
var args = require("yargs")
    .usage("$0 endpoint")
    .demand(1)
    .argv;
var logger = require("../lib/log");
var t = require("../lib/client");

var sock = io.connect(args._[0], {transports: ["websocket"]});

sock.on("state-changed", function(msg) { logger.info("state-changed", msg)});
sock.on("trial-data", function(msg) { logger.info("trial-data", msg)});

sock.once("disconnect", function() { logger.info("disconnected from", args._[0])})
sock.once("connect", function() {
    logger.info("connected to ", args._[0])
    repl.start({
        prompt: "node> ",
        input: process.stdin,
        output: process.stdout
    })
    .on("exit", function() { sock.disconnect();})
    .context.sock = sock;
})
Example #2
0
var io = require('socket.io-client');
var crypto = require('crypto');
var randomAccessFile = require('random-access-file');


var uid = process.argv[2];
if(!uid) {
  var usage = 'Usage:\n' +
    '  node uploader.js [MY_UID]\n';
  console.log(usage);
  process.exit(1);
}


var serverAddress = 'http://127.0.0.1:8099';
var socket = io.connect(serverAddress);
var DB = {'123': 'xingxing.mp3'}

socket.emit('LOGIN', uid);
socket.on('RECV' + uid, function(msg) {
  var filehash = msg.content.filehash;
  var filesize = msg.content.filesize;
  var blockindex = msg.content.blockindex;
  var blocksize = msg.content.blocksize;

  if(filehash in DB) {
    var file = randomAccessFile(DB[filehash]);
    var isCompleteBlock = filesize-blockindex*blocksize === blocksize;
    var readsize = isCompleteBlock ? blocksize : filesize-blockindex*blocksize;
    file.read(blockindex*blocksize, readsize, function(err, data) {
      if(err) {
Example #3
0
function SimpleWebRTC(opts) {
    var self = this;
    var options = opts || {};
    var config = this.config = {
            url: 'http://signaling.simplewebrtc.com:8888',
            debug: false,
            localVideoEl: '',
            remoteVideosEl: '',
            enableDataChannels: true,
            autoRequestMedia: false,
            autoRemoveVideos: true,
            adjustPeerVolume: true,
            peerVolumeWhenSpeaking: 0.25
        };
    var item, connection;

    // We also allow a 'logger' option. It can be any object that implements
    // log, warn, and error methods.
    // We log nothing by default, following "the rule of silence":
    // http://www.linfo.org/rule_of_silence.html
    this.logger = function () {
        // we assume that if you're in debug mode and you didn't
        // pass in a logger, you actually want to log as much as
        // possible.
        if (opts.debug) {
            return opts.logger || console;
        } else {
        // or we'll use your logger which should have its own logic
        // for output. Or we'll return the no-op.
            return opts.logger || mockconsole;
        }
    }();

    // set our config from options
    for (item in options) {
        this.config[item] = options[item];
    }

    // attach detected support for convenience
    this.capabilities = webrtcSupport;

    // call WildEmitter constructor
    WildEmitter.call(this);

    // our socket.io connection
    connection = this.connection = io.connect(this.config.url);

    connection.on('connect', function () {
        self.emit('connectionReady', connection.socket.sessionid);
        self.sessionReady = true;
        self.testReadiness();
    });

    connection.on('message', function (message) {
        var peers = self.webrtc.getPeers(message.from, message.roomType);
        var peer;

        if (message.type === 'offer') {
            if (peers.length) {
                peer = peers[0];
            } else {
                peer = self.webrtc.createPeer({
                    id: message.from,
                    type: message.roomType,
                    sharemyscreen: message.roomType === 'screen' && !message.broadcaster
                });
            }
            peer.handleMessage(message);
        } else if (peers.length) {
            peers.forEach(function (peer) {
                peer.handleMessage(message);
            });
        }
    });

    connection.on('remove', function (room) {
        if (room.id !== self.connection.socket.sessionid) {
            self.webrtc.removePeers(room.id, room.type);
        }
    });

    // instantiate our main WebRTC helper
    // using same logger from logic here
    opts.logger = this.logger;
    opts.debug = false;
    this.webrtc = new WebRTC(opts);

    // attach a few methods from underlying lib to simple.
    ['mute', 'unmute', 'pause', 'resume'].forEach(function (method) {
        self[method] = self.webrtc[method].bind(self.webrtc);
    });

    // proxy events from WebRTC
    this.webrtc.on('*', function () {
       self.emit.apply(self, arguments);
    });

    // log all events in debug mode
    if (config.debug) {
        this.on('*', this.logger.log.bind(this.logger, 'SimpleWebRTC event:'));
    }

    // check for readiness
    this.webrtc.on('localStream', function () {
       self.testReadiness();
    });

    this.webrtc.on('message', function (payload) {
       self.connection.emit('message', payload);
    });

    this.webrtc.on('peerStreamAdded', this.handlePeerStreamAdded.bind(this));
    this.webrtc.on('peerStreamRemoved', this.handlePeerStreamRemoved.bind(this));

    // echo cancellation attempts
    if (this.config.adjustPeerVolume) {
        this.webrtc.on('speaking', this.setVolumeForAll.bind(this, this.config.peerVolumeWhenSpeaking));
        this.webrtc.on('stoppedSpeaking', this.setVolumeForAll.bind(this, 1));
    }

    if (this.config.autoRequestMedia) this.startLocalVideo();
}
Example #4
0
var started = false;
var random = require("random");
var youtube = require('youtube-feeds');
var users = [];
var chatBuffer = [];
var chance = 60;
var edge = 0.97; // EV + 2% tip fee
var payout = 1.4;
var qlist = "";
var qgame = false;
var qboss = 'Game not in progress';
var tippedProfit = true;
var toproom = 'botgames';
var shutdown = false;
var lastWinner = null;
var socket = io.connect("http://192.155.86.153:8888/");
console.log('Connecting...');
var reconnectTimeout = setTimeout(function() {
    console.log('Lagged out, rebooting');
    process.exit(1)
}, 10000);
socket.on("connect", function() {
    console.log('Connected');
    clearTimeout(reconnectTimeout);
    socket.on("message", function(msg) {
	console.log('SERVER MESSAGE: ' + msg.message);
	if (msg === "You have been banned.") {
	    console.log('Error: Banned!');
	    process.exit(1);
	}
    });
Example #5
0
let dbService;
let socket;

if(config.system.argvParser){
  let argvParser = require('./scripts/argv-parser');
  $argv = argvParser(process.argv);
}

process.title = config.system.processName;
let dbServices = {
  mongoDB:'mongoose',
  firebase:['firebase' , 'firebase-admin']
}

if(config.gulp.socket){
  socket = socketIOClient.connect(`http://localhost:${config.system.port}`);
  socket.emit('process-connected', {name:'main', pid:process.pid})
}


// if(config.processes.firebase.database){
//   console.log(`firebase enabled`.yellow)
//   console.log(`firebase DB workspace created at ${config.firebase.workspace}`.yellow);
//   console.log(`use /firebase to connect`.yellow);
//   require('./scripts/firebase-client');
// }

for(let iScript in integatedScripts){
  let iConfig = integatedScripts[iScript];
  let getOptions  = config.integrated[iScript];
Example #6
0
 beforeEach(function(done) {
   client = io.connect(socketUrl, options);
   client2 = io.connect(socketUrl, options);
   done();
 });
Example #7
0
File: syr.js Project: Eisbaeeer/Syr
var syrSettings = settings.adapters.syr.settings;

//Global vars require
var logger = require(__dirname+'/../../logger.js'),
    io     = require('socket.io-client'),
    fs     = require("fs"),
	  net    = require('net');

//Global vars
var objects = {},
    result = {},
	  datapoints = {};
    
if (settings.ioListenPort) {
	var socket = io.connect("127.0.0.1", {
		port: settings.ioListenPort
	});
} else if (settings.ioListenPortSsl) {
	var socket = io.connect("127.0.0.1", {
		port: settings.ioListenPortSsl,
		secure: true
	});
} else {
	process.exit();
}


socket.on('connect', function () {
    logger.info("info", "connected to ccu.io");
});
Example #8
0
var backend = "backend-url";
var ui = "mobile-angular-url";

var gcm = require('node-gcm'); 
var io  = require('socket.io-client');
var socket = io.connect(backend);

var sender = new gcm.Sender('API-Access-Key');
var registrationIds = [];
registrationIds.push("GCM-Registration-ID");

socket.on('connect', function(){
	console.log("Listening to messages");
});

socket.on('commands:new', function(command) {
	var entityId = command.data.id;
	var content = "La mission #"+entityId+" a été modifiée";
	var url = ui+"/#/mission/"+entityId+"?page=mission";
	var message = new gcm.Message({
		collapseKey: 'demo',
		delayWhileIdle: true,
		timeToLive: 3,
		data: {
			content: content,
			url: url
		}
	});

	sender.sendNoRetry(message, registrationIds, function (err, result) {
		if(err)
var io = require('socket.io-client');
var socket = io.connect('http://localhost:9500');
var _ = require('underscore');

socket.emit('get_config_test',{});

socket.on('set_config_test', function(msg){
    var all_left = _.all(msg, function(item){
      if (item.color==="blue" || item.color ==="yellow" ) {
        return (item.float === "left" && (item.clear === "left" || item.clear === "both"));
      } else {
        return (item.float === "left" && item.clear === "none");
      }
    });
  
    if (all_left) {
      process.stdout.write('Well done!\n');
      process.exit(0);
    } else {
      process.stdout.write('All balloons should be making a C like in the picture!\n');
      process.exit(1);
    }
});





    host: 'localhost',
    port: 9016
  }
});

var proxyServer = http.createServer(function (req, res) {
  proxy.web(req, res);
});

//
// Listen to the `upgrade` event and proxy the
// WebSocket requests as well.
//
proxyServer.on('upgrade', function (req, socket, head) {
  setTimeout(function () {
    proxy.ws(req, socket, head);
  }, 1000);
});

proxyServer.listen(8016);

//
// Setup the socket.io client against our proxy
//
var ws = client.connect('ws://localhost:8016');

ws.on('message', function (msg) {
  util.debug('Got message: ' + msg);
  ws.send('I am the client');
});
Example #11
0
Crash.prototype.connect = function() {

  this.socket = io.connect(this.config.socketio.uri, this.config.socketio.config);
  this.listen();
};
Example #12
0
this.connect = function(protocol, host, port, session, mode, token, eventBus) {
  var eb = eventBus;

  var socketUrl =  protocol + '//' + host + ":" + port + '/' + mode;
  this.socket = io.connect(socketUrl, { 
    'query': 'token=' + token+'&asq_sid=' + session 
  });

  this.socket
  .on('connect', function onConnect(evt) {
    eb.emit('socket:connect', evt);
  })

  .on('asq:sessionFlow', function onSessionFlow(evt) {
    eb.emit('asq:sessionFlow', evt);
  })

  .on('asq:answered-all', function onAnsweredAll(evt){
    eb.emit('asq:answered-all', evt);
  })

  .on('asq:user-session-stats', function onUserSessionStats(evt){
    eb.emit('asq:user-session-stats', evt);
  })

  .on('asq:rankings', function onRankings(evt){
    eb.emit('asq:rankings', evt);
  })

  /**
   Handle socket event 'goto'
   Uses impress.js API to go to the specified slide in the event.
   */
  .on('asq:goto', function onGoto(evt) {
    eb.emit('asq:goto', evt);
  })

  /**
   Indicate a submission was accepted.
   **/
  .on('asq:submitted', function onSubmitted(evt) {
    eb.emit('asq:submitted', evt);
  })

  /**
  * Received assessment for self
  */
  .on('asq:assessment', function onAssessment(evt){
    eb.emit('asq:assessment', evt);
  })

  .on('asq:assess', function onAssess(evt) {
    eb.emit('asq:assess', evt);
  })

  .on('asq:stat', function onStat(evt) {
    eb.emit('asq:stat', evt);
  })

  /**
    Generic event to be consumed by interested question types
  */
  .on('asq:question_type', function onQuestionType(evt){
    eb.emit('asq:question_type', evt);
  })

  .on('asq:session-terminated', function sessionTerminated(evt) {
    eb.emit('asq:session-terminated', evt);
  })

  // TODO: check if the following three exist
  .on('disconnect', function onDisconnect(evt) {
    eb.emit('socket:disconnect', evt);
  })

  .on('reconnect_attempt', function(evt) {
    console.log(evt)
    eb.emit('socket:reconnect_attempt', evt);
  })

    .on('connect_error', function(evt) {
    console.log(evt)
    eb.emit('socket:connect_error', evt);
  })

  .on('connect_failed', function(evt) {
    console.log(evt)
    eb.emit('socket:connect_error', evt);
  })

  .on('error', function (evt){
    console.log(evt)
    eb.emit('socket:error', evt);
  });
}
Example #13
0
 function startconn() {    // Connect to remote endpoint
   var socket = ioclient.connect(node.path, {multiplex: false});
   node.server = socket; // keep for closing
   handleConnection(socket);
 }
var io = require('socket.io-client');
var assert = require('assert')
var port = 8081;
var serverUrl = 'http://localhost:8081/test';
var socket = io.connect(serverUrl);

// send a message to the server
socket.emit('PING', { message: 'ping from nodejs socketIO'  });


socket.on('PONG', function(data) {
        //print the data send by the server
         console.log("data: ",data.message);
        //                           document.getElementById('out').innerHTML = data_socket_IO.message ;
        //
        assert.equal(data.message,"ping from nodejs socketIO from server")
	process.exit(0);
                                                });
Example #15
0
			'energy',
			'rotationRate'
			)
		.then((modules) => {
			const energy = modules[0];
			const rotationRate = modules[1];
			//feedInputChain(energy);
			feedInputChain(rotationRate);
		})
		.catch((err) => console.error(err.stack));
})();

// ================= socket operations ================== //

//let socket = io.connect('http://169.254.68.117:3000');
let socket = io.connect(location.host + '/wiml-client');
//let socket = io.connect('127.0.0.1:3000');

socket.on('confirm', (message) => {
	console.log('server confirms reception of message :');
	console.log(message);
});

// this could be probably improved (kind of callback from xmm)
socket.on('train', (message) => {
	if(message === 'ok') {
		// training worked, can request new models
	} else {
		console.error(message);
	}
})
Example #16
0
'use strict';

// I used tomatpasser's gpio-buttons plugin as a basis for this project
var libQ = require("kew");
var fs = require("fs-extra");
var Gpio = require("onoff").Gpio;
var config = new (require("v-conf"))();
var io = require('socket.io-client');
var sleep = require('sleep');
var socket = io.connect("http://localhost:3000");
var execSync = require('child_process').execSync;

// Event string consts
const SYSTEM_STARTUP = "systemStartup";
const SYSTEM_SHUTDOWN = "systemShutdown";
const MUSIC_PLAY = "musicPlay";
const MUSIC_PAUSE = "musicPause";
const MUSIC_STOP = "musicStop";

// Events that we can detect and do something
const events = [SYSTEM_STARTUP, SYSTEM_SHUTDOWN, MUSIC_PLAY, MUSIC_PAUSE, MUSIC_STOP];

module.exports = GPIOControl;

// Constructor
function GPIOControl(context) {
	var self = this;

	self.context = context;
	self.commandRouter = self.context.coreCommand;
	self.logger = self.context.logger;
var Logger = require('./the-future-logger.js').TFLogger;
Logger.getNewLog('find-path-payment-no-control');

var io = require('socket.io-client');
var fpio = io.connect('http://localhost:3000/fp');

var math = require('mathjs');
var _ = require('underscore');
var events = require('events');

var config = require('./config.js');
var ripple = require('../src/js/ripple');
var crypto = require('./crypto-util.js');
var jsbn = require('../src/js/jsbn/jsbn.js');
var mongodbManager = require('./the-future-manager.js');
var PathFind = require('../src/js/ripple/pathfind.js').PathFind;


var emitter = new events.EventEmitter();
emitter.on('txComplete', txComplete);

var servers = [{
    host: 's-east.ripple.com',
    port: 443,
    secure: true
}, {
    host: 's-west.ripple.com',
    port: 443,
    secure: true
}, {
    host: 's1.ripple.com',
Example #18
0
var client = require('socket.io-client')
  , replify = require('replify')

var cid = process.argv[2] || 'x'
  , socket = client.connect('http://localhost:8888')

socket.on('connect', function () {
  console.log('client %d connected', cid)
  socket.emit('join', cid)
})

replify('socket.io-client_'+cid, socket)
Example #19
0
var
    io = require('socket.io-client'),
    ioClient = io.connect('http://localhost:9300');

var positionX = 0;
var positionY = 300;
var mowe = true;

setInterval(function() {

	if(positionX >= 1024){
		mowe = false;
	}else if(positionX <= 1) {
		mowe = true;
	}

	if(mowe){
		positionX++;
	}else{
		positionX--;
	}
	var data = {
		x: positionX,
		y: positionY,
		status: false
	}

	ioClient.emit('message', data);

}, 1000);
Example #20
0
// Of course we need the socket.io-client library
var io = require('socket.io-client');
// We need the fs library to be explicitly required for config.json to be read
var fs = require('fs');
// This reads the contents of config.json and parses it into an array.
var config = JSON.parse(fs.readFileSync('config.json').toString());
// This connects to the IP and port specified in config.json
// You can get the botkey parameter (config.json:key) from using /botkey in Nodechat
var socket = io.connect('http://' + config.ip + ':' + config.port + '?botkey=' + config.key);
var isModerator;

// The 'connect' event is built-in to socket.io-client
socket.on('connect', function() { // This tells us when we actually connect.
	console.log('Connected to ' + config.ip + ':' + config.port); // You can put initial calls to socket.emit here.
});

socket.on('connect_failed', function() { // This is so that a failed connection won't kill the program silently.
	console.log('Connection to ' + config.ip + ':' + config.port + ' failed.');
});

// Handles the 'loginStatus' part of the protocol
socket.on('loginStatus', function(data) {
	if (data.isLoggedIn !== true) { // It's no good if the key is not valid, so we check for that
		console.log('Error: user is banned or key is invalid.');
		return;
	}
	console.log('Connection successful.');
	if (data.isForumModerator === true) { // We want to see if our bot is a moderator, and if so, keep track of that.
		isModerator = true;
	}
});
Example #21
0
var io = require('socket.io-client')
module.exports = io.connect()
Example #22
0
    });
    return driving.length === 0 ? {} : driving[0];
});
localServer('awake', function () {
    return _.keys(T('servers')).length > 0;
});

var host = config.HOST;

if (process.env.PETBOT_HOST == 'ssh_auto') {
    host = 'http://' + process.env.SSH_CLIENT.split(' ')[0];
    console.log('auto host: ' + host);
}

var nextId = 1;
var socket = client.connect(host, { transports: ['xhr-polling'] });
socket.on('connect', function() {
    var me = tbone.make();
    me('id', nextId++);
    servers.add(me);

    console.log('connected to remote server');
    socket.emit('clientId', {id: config.DEVICE_ID});

    // Expect the server to say "keepDriving" every ~500 ms.
    var driveTimeout;
    function stopDrivingAfterTimeout() {
        if (driveTimeout) {
            clearTimeout(driveTimeout);
        }
        driveTimeout = setTimeout(function () {
Example #23
0
// var path = d3.geo.path()
//     .projection(projection);

var path = d3.geo.path()
    .projection(d3.geo.mercator()
    .scale(20000)
    .translate([0, 3800]));

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);



var socket = io.connect('localhost:5000');

btn.onclick = function () {
  socket.emit('gimme'); 
}

var osm;
socket.on('data', function (data) {
  // osm = JSON.parse(data);
  osm = data;
  data.features.forEach(function (feature) {
    if (feature.properties.tags.hasOwnProperty('highway')) {
      return 
    }
    console.log(feature)
  })
Example #24
0
var prompt = require('prompt'),
    io = require('socket.io-client'),
    fileExists = require('file-exists'),
    fs = require('fs');

var url = 'http://127.0.0.1:8080';
var options = {
    transports: ['websocket'],
    'force new connection': true
};

let client = io.connect(url, options);

let maleAccessToken = 'LurenAccessDev123';
let femaleAccessToken = 'AliceAccessDev123';

let maleSecretPath = 'male_secret.txt';
let femaleSecretPath = 'female_secret.txt';

let myUsername;
let myGender;
let myAccessToken;
let mySecretPath;
let lat = 38.88;
let lon = -77.17;

if (process.argv.length == 3) {
    if (process.argv[2] == '--reset') {

        if (fileExists(maleSecretPath)) {
            fs.unlink(maleSecretPath, (err) => {
var io = require('socket.io-client');

var serverUrl = 'http://localhost:8080/';
var conn = io.connect(serverUrl);

conn.on('connect', function(socket) { 
    console.log('Connected!');
    conn.emit('evento', 'data enviada', function(resp, data) {
        console.log('server sent resp code ' + resp+ ' ' + data);
    });
});

Example #26
0
const openSocket = _ => io.connect(`${apiConfig.host}/`, { query: `token=${getToken()}` });
Example #27
0
 it("able to connect on port 3000", function (done) {
   var client = io.connect(socketURL, options);
   done();
 });
Example #28
0
var io = require('socket.io-client');
var socket = io.connect('lostlandmarks.cc', { port: 9001, reconnect: false });

var connectionTimer = setInterval(socketReconnect, 5000);

var exec = require('child_process').exec;
var child;

var queue = [
	'armory.mov',
	'doc-video.mov',
	'grand-central.mov',
	'doc-video.mov',
];
var index = 0;

var nextVideo = function() {
	console.log("Playing", queue[index]);

	if (queue[index].indexOf('doc-video') == -1) {
		socket.emit('message', { event: 'change-content', value: queue[index].split('.')[0] });
	}

	child = exec('omxplayer ' + queue[index], function (error, stdout, stderr) {
	    // console.log('stdout: ' + stdout);
	    // console.log('stderr: ' + stderr);
	    if (error !== null) {
	      console.log('exec error: ' + error);
	    }
	    
	    index = ++index % queue.length;
Example #29
0
function MilfeeSocket(host, init_cb) {
    var self = this;
    this.app_id = host.split('.')[0];
    this.callback_id = 0;
    this.callbacks = {};
    this.listeners = {
        push : {},
        set : {},
        remove : {},
        send : {}
    };
    this.host = host;
    this.socket = client.connect(host, {
        'reconnect': true,
        'reconnection delay': 500,
        'max reconnection attempts': 10,
        'force new connection': true,
        "transport": "websocket"
    });
    this.reconnect_count = 0;
    this.queue = [];
    this.mode = 'offline';  //online or offline
    this.idGenerator = new IdGenerator();
    this.socket.on('connect', function() {
        console.log('connected');
        self.reconnect_count++;
        if(self.reconnect_count <= 1) {
            if(init_cb) init_cb();
        }
        self.socket.on('init', function(data) {
            self.idGenerator.init(data.ts);
            self.fire_operations();
        });
        self.socket.on(eventnames.callback, function(a) {
            var callbackid = "a" + String(a.callback_id);
            if(self.callbacks[callbackid]) {
                self.callbacks[callbackid](a.docs);
            }
        });
        self.socket.on(eventnames.push, function(a) {
            for(var i=0;i < self.listeners.push[a.sys.path].length;i++) {
                self.listeners.push[a.sys.path][i](a);
            }
        });
        self.socket.on(eventnames.set, function(a) {
            for(var i=0;i < self.listeners.set[a.sys.path].length;i++) {
                self.listeners.set[a.sys.path][i](a);
            }
        });
        self.socket.on(eventnames.remove, function(a) {
            for(var i=0;i < self.listeners.remove[a.sys.path].length;i++) {
                self.listeners.remove[a.sys.path][i](a);
            }
        });
        self.socket.on(eventnames.send, function(a) {
            for(var i=0;i < self.listeners.send[a.sys.path].length;i++) {
                self.listeners.send[a.sys.path][i](a);
            }
        });
    });
}
Example #30
0
// var io = require('../src/vendor/socket.io');
var io = require('socket.io-client');
socket = io.connect('http://localhost:5001');


socket.on('connect', function() {
    socket.emit('message', {hello: 'world'});
})