Esempio n. 1
0
    value: function connect(proxyServer) {
      var _this2 = this;

      this.logger.debug(('Connecting bot ' + this.name + ' (' + this.server + ')').yellow);
      this.proxyServer = proxyServer;

      var client = new _websocket.client();
      var requestOptions = {};

      // Tunnel through proxy server if the option is there
      if (typeof proxyServer === 'string') {
        var AUTH = process.env.PROXY_AUTH || null;
        var mode = 'http';
        if (proxyServer.indexOf('socks') === 0) {
          mode = 'socks';
        }

        if (mode === 'http') {
          var proxy = {
            host: proxyServer,
            port: 80
          };

          var idx = proxy.host.indexOf(':');
          if (idx > 0) {
            proxy.port = proxy.host.substring(idx + 1);
            proxy.host = proxy.host.substring(0, idx);
          }

          if (AUTH) {
            proxy.proxyAuth = AUTH;
          }

          requestOptions.agent = _tunnel2.default.httpOverHttp({
            proxy: proxy
          });
        } else if (mode === 'socks') {
          // if(AUTH) {
          //   const idx = proxyServer.indexOf('socks://')
          //   proxyServer = `socks://${AUTH}@${proxyServer.substring(idx + 8)}`
          // }
          //
          // requestOptions.agent = new SocksProxyAgent(proxyServer)
          // this.logger.debug('[%s] Using %s proxy server', this.name, mode)
        }
      } else if ((typeof proxyServer === 'undefined' ? 'undefined' : _typeof(proxyServer)) === 'object') {
          requestOptions.agent = proxyServer;
        }

      // connectFailed
      client.on('connectFailed', function (err) {
        _this2.logger.debug('[%s] %s', _this2.name, err);

        _this2.emit('error', err);
        _this2.emit('errorConnect', err);
      });

      client.on('connect', this.onConnect.bind(this));
      client.connect('ws://' + this.server + '/slither', null, 'http://slither.io', null, requestOptions);
    }
Esempio n. 2
0
  init: function(cb) {
    var self = this;

    this._reqs = {};
    this._channels = {};

    var client = new WebSocketClient();

    client.on('connectFailed', function(error) {
      console.log('Connect Error: ' + error.toString());
    });

    client.on('connect', function(connection) {
      console.log('WebSocket client connected');

      self._connection = connection;

      connection.on('error', function(error) {
        console.log('Connection Error: ' + error.toString());
      });

      connection.on('close', function() {
        console.log('push-notification Connection Closed');
      });

      connection.on('message', self._handleMessage.bind(self));

      // Begin the handshake
      self._hello(cb);
    });

    client.connect(this._wsHost, 'push-notification');
  },
Esempio n. 3
0
    function createPublisher(subject){
        var client = new WebSocketClient();

        client.on('connect', function(connection) {
            countPubs += 1;
            connection.on('error', function(error) {
                console.log("Connection Error: " + error.toString());
            });
            connection.on('close', function() {
                console.log('Connection Closed');
            });

            function updateSubject() {
                if (connection.connected && isPublishing) {
                    //console.log('Sent: ' + subject);
                    connection.sendUTF(JSON.stringify({
                        type: "publisher",
                        "object": subject,
                        published: +new Date()
                    }));
                }
            }

    		setInterval(updateSubject, sendingPeriod);
        });

        client.on('connectFailed', function(error) {
            countFailedPubs += 1;
            console.log('Connect Error: ' + error.toString());
        });
        client.connect('ws://' + host + ':' + port + '/', 'echo-protocol');
    }
Esempio n. 4
0
this.makeQuery = function(data, response, request){

	response.writeHead(200,{'Content-Type': 'application/octet-stream'});

	console.log("The processing has successfully reached the twitterQuery.js function")
	console.log(data);
	console.log("\n");
	

	// The response was passed from the dispatcher. It comes from the asynchronous call
	// from the user -- Note that the websocket connection is nested inside this 
	// client-server relationship. 

	var client = new WebSocketClient();

 	client.on('connectFailed', function(error){
 		console.log('Connect error: ' + error.toString());
 		response.end();
 	});


 	client.on('connect', function(connection){

 		connection.on('message', function(message) {

 			console.log("From server: '"); 
 			console.log(message.utf8Data + "'");
 			console.log("\n");
			response.write(message.utf8Data);

 		});

 		connection.on('close',function(){
 			response.end();
 			console.log("The connection closed.")
 		})

		request.on('close', function(){
			console.log('The user aborted its request.')
			connection.close();
		});

 		function sendParameters(){
 			if (connection.connected){
 				console.log("Sending data: " + JSON.stringify(data));
	  			console.log("\n");			
 				connection.sendUTF(JSON.stringify(data)); 
 				// Uncomment below to kee calling function.
 				//setTimeout(sendParameters,1000);
 			}
 		};

 		sendParameters();

 	});

	client.connect('ws://localhost:8080/', 'echo-protocol', 'twitterQuery');


};
Esempio n. 5
0
function createClient(index){
    var client = new WebSocketClient();
    var randomSubjects = getRandomSubjects();
    //console.log("client with instanceno " + instanceNo + " has these random subjects");
    for (var i = 0; i < randomSubjects.length; i++) {
        console.log(randomSubjects[i]);
    }
    client.on('connect', function(connection) {
        //console.log('WebSocket client connected instanceno: ' + instanceNo);
        connection.on('error', function(error) {
            console.log("Connection error on client "+ index + ". " + error.toString());
        });
        connection.on('close', function() {
            connectionsClosed++;
            console.log('Connection Closed with description ' + connection.closeDescription);
        });
        connection.on('message', function(message) {
            if (message.type === 'utf8') {
                //console.log(index + "=" + message.utf8Data);
                var data = JSON.parse(message.utf8Data);
                var elapsed = +new Date() - data.message;
                stats.push(elapsed);
            }
        });
        connection.sendUTF(JSON.stringify({type:"client", object:randomSubjects}));
    });

    client.on('connectFailed', function(error) {
        connectionsFailed++;
        console.log('Connect failed on client ' + index + ". " + error.toString());
    });
console.log('ws://' + host + ':' + port + '/', 'echo-protocol');
    client.connect('ws://' + host + ':' + port + '/', 'echo-protocol');
}
Esempio n. 6
0
    function createSubscriber(subject){
        var client = new WebSocketClient();

        client.on('connect', function(connection) {
            countSubs += 1;
            connection.on('error', function(error) {
                console.log("Connection error on client "+ subject + ". " + error.toString());
            });
            connection.on('close', function() {
                console.log('Connection Closed with description ' + connection.closeDescription);
            });
            connection.on('message', function(message) {
                if (message.type === 'utf8') {
                    var data = JSON.parse(message.utf8Data);
                    stats.push(data.message + " " + Date.now() + " " + cluster.worker.id);
                }
            });
            connection.sendUTF(JSON.stringify({
                type: "client",
                object: [subject]
            }));
        });

        client.on('connectFailed', function(error) {
            countFailedSubs += 1;
            console.log('Connect failed on client ' + subject + ". " + error.toString());
        });
        client.connect('ws://' + host + ':' + port + '/', 'echo-protocol');
    }
Esempio n. 7
0
//initiates websocket connection
function createWS(url) {
    let client = new WebSocketClient();

    client.on('connectFailed', function(error) {
        log('Connect Error: ' + error.toString());
    });

    client.on('connect', function(conn) {
        connection = conn;
        log('WebSocket Client Connected');

        connection.on('error', function(error) {
            log("Connection Error: " + error.toString());
        });

        connection.on('close', function() {
            log('echo-protocol Connection Closed');
        });

        connection.on('message', function(message) {
            if (message.type === 'utf8') {
                handleMessage(JSON.parse(message.utf8Data), message);
            }

        });
    });
    client.connect(url);
    log("hey?");

}
Esempio n. 8
0
/**********************************************************************
* wsCommunication
**********************************************************************/
function wsCommunication(){
    spc_ws_client.connect('wss://' + config.spc_gw_host + ':' + 
                         config.spc_gw_port + '/ws/spc?username='******'&password='******'connectFailed', function(error) {
        console.log('Connect Error: ' + error.toString());
    });

    spc_ws_client.on('connect', function(connection) {
        console.log('SPC WebSocket client connected');

        connection.on('error', function(error) {
            console.log("Connection Error: " + error.toString());
        });
        connection.on('close', function() {
            console.log('echo-protocol Connection Closed');
        });
        connection.on('message', function(message) {
            if (message.type === 'utf8') {
                manageSiaEvent(message.utf8Data);
            }
        });
    });
}
Esempio n. 9
0
      function connect() {
         var client = new WebSocketClient();

         client.on('connectFailed', function (error) {
            console.log('connectFailed: ' + error.toString());
            setTimeout(connect, 5000);
         });

         client.on('connect', function (connection) {
            console.log('WebSocket Client Connected :' + id);
            connection.on('error', function (error) {
               console.log("Connection Error: " + error.toString());
               setTimeout(connect, 5000);
            });
            connection.on('close', function () {
               console.log('echo-protocol Connection Closed ' + id);
            });
            connection.on('message', function (message) {
               if (message.type === 'utf8') {
                  console.log(id + " Received: '" + message.utf8Data + "'");
                  var msg = JSON.parse(message.utf8Data);
                  // TODO now validate the signed message
                  events.emit("message", msg);
               }
            });
				
            // register with its id in order to be able to get messages
            connection.sendUTF(JSON.stringify({ cmd: "init", adr: id, ips: getIpAdresses() }));
         });
			
         // start connection...
         client.connect('ws://' + wsConfig.host + ':' + wsConfig.port + '/', 'echo-protocol');
      }
Esempio n. 10
0
function WebSocket(url) {
  this.readyState = 0;
  var client = new WebSocketClient();
  this.onconnect = this.onconnect.bind(this);
  client.once('connect', this.onconnect);
  client.once('connectFailed', this.emit.bind(this, 'close'));
  client.connect(url);
}
Esempio n. 11
0
  connect(proxyServer) {
    this.logger.debug(`Connecting bot ${this.name} (${this.server})`.yellow)
    this.proxyServer = proxyServer

    const client = new WebSocketClient()
    const requestOptions = {}

    // Tunnel through proxy server if the option is there
    if(typeof proxyServer === 'string') {
      const AUTH = process.env.PROXY_AUTH || null
      let mode = 'http'
      if(proxyServer.indexOf('socks') === 0) {
        mode = 'socks'
      }

      if(mode === 'http') {
        const proxy = {
          host: proxyServer,
          port: 80
        }

        let idx = proxy.host.indexOf(':')
        if(idx > 0) {
          proxy.port = proxy.host.substring(idx + 1)
          proxy.host = proxy.host.substring(0, idx)
        }

        if(AUTH) {
          proxy.proxyAuth = AUTH
        }

        requestOptions.agent = tunnel.httpOverHttp({
          proxy
        })
      } else if(mode === 'socks') {
        // if(AUTH) {
        //   const idx = proxyServer.indexOf('socks://')
        //   proxyServer = `socks://${AUTH}@${proxyServer.substring(idx + 8)}`
        // }
        //
        // requestOptions.agent = new SocksProxyAgent(proxyServer)
        // this.logger.debug('[%s] Using %s proxy server', this.name, mode)
      }
    } else if(typeof proxyServer === 'object') {
      requestOptions.agent = proxyServer
    }

    // connectFailed
    client.on('connectFailed', err => {
      this.logger.debug('[%s] %s', this.name, err)

      this.emit('error', err)
      this.emit('errorConnect', err)
    })

    client.on('connect', this.onConnect.bind(this))
    client.connect(`ws://${this.server}/slither`, null, 'http://slither.io', null, requestOptions)
  }
Esempio n. 12
0
function createClient(count){
	var client = new WebSocketClient();
 
	client.on('connectFailed', function(error) {
	    console.log('Connect Error: ' + error.toString());
	});
 
	client.on('connect', function(connection) {
	    console.log('WebSocket Client Connected: ', count);
	    connection.on('error', function(error) {
	        console.log("Connection Error: " + error.toString());
	    });
	    connection.on('close', function() {
	        console.log('echo-protocol Connection Closed');
	    });
	    connection.on('message', function(data) {
	
			var message = JSON.parse(data["utf8Data"]);
			
			console.log(message)
			if(message.method =='login'){
				var message = {};
				message.method  = "joinSpace";
				message.sid = "507f191e810c19729de860ec";
				connection.send(JSON.stringify(message));	
				
				setInterval(function(){
					var message = {};
					message.method  = "addpost";
					message.text  = casual.sentences(casual.integer(1,10));
					message.spaces = ["507f191e810c19729de860ec"];
					connection.send(JSON.stringify(message));	
				}, casual.integer(60000,120000))
				
				
			}
			
			
			
			
			
	    });
    
	    function login() {
	        if (connection.connected) {
				var message = {};
				message.method  = "login";
				message.username = "******" + count;
				message.password = "******" + count;
				connection.send(JSON.stringify(message));
	        }
	    }
	    login();
	});
 
	client.connect('ws://localhost:3000/', 'echo-protocol');
}
Esempio n. 13
0
function makeMetaSocket() {
    var WebSocketClient = require('websocket').client;
    var metaSocket = new WebSocketClient();
    metaSocket.on('connectFailed', function(error) {
        console.log('>> Connection ' + error.toString());
        process.exit();
    });
    return metaSocket;
}
Esempio n. 14
0
WsRewriter.prototype._handleWsRequest = function(req) {
    debug('ws-server connection request');

    var self = this;
    var servConn = req.accept(null, req.origin); // accept from all origins
    setupWSLogging(servConn);

    var pendingServMsgs = [];
    function handleServMsg(data) {
        pendingServMsgs.push(data);
    }
    servConn.on('message', handleServMsg);

    function handleServClose(reasonCode, desc) {
        // client/browser closed before we established connection to kernel gateway
        wsclient.abort();
    }
    servConn.on('close', handleServClose);

    // for every WS connection request from the client/browser, create a new connection to
    // the kernel gateway
    var wsclient = new WebSocketClient({
        maxReceivedFrameSize: Number.MAX_SAFE_INTEGER,
        maxReceivedMessageSize: Number.MAX_SAFE_INTEGER,
        fragmentationThreshold: FRAGMENTATION_THRESHOLD
    });

    wsclient.on('connect', function(clientConn) {
        debug('ws-client connected');
        setupWSLogging(clientConn);
        // connected to kernel gateway -- now setup proxying between client/browser & gateway
        self._setupProxying(servConn, clientConn);
        // delete listeners that are no longer necessary
        servConn.removeListener('message', handleServMsg);
        servConn.removeListener('close', handleServClose);
        // handle pending messages
        pendingServMsgs.forEach(function(data) {
            sendSocketData(clientConn, data);
        });
    });

    wsclient.on('connectFailed', function(e) {
        // failed to connect to kernel gateway -> close connection to client/browser
        error('ws client connect failure', e);
        if (servConn.connected) {
            servConn.drop(WebSocketConnection.CLOSE_REASON_INTERNAL_SERVER_ERROR,
                'Failed to create websocket connection to kernel gateway');
        }
    });

    // kick off connection to kernel gateway WS
    var url = urljoin(this._host, this._basePath, req.resourceURL.path).replace(/^http/, 'ws');
    wsclient.connect(url, null, null, this._headers);

    this.emit('request', req, servConn);
};
Esempio n. 15
0
/*Test web socket functionality*/
function socketTest(){

	var deferred = q.defer();
	var WebSocketClient = require( 'websocket' ).client;

	var client = new WebSocketClient();


	client.on( 'connectFailed', function( error ){

		console.log( 'Connection error: '.red + error.red);
		deferred.resolve( false );
	});

	client.on( 'connect', function( connection ){

		console.log( 'Websocket client connected' );
		connection.on( 'error', function( error ){

			console.log('Connection error: ' + error.toString() );
			deferred.resolve( false );
		} );

		connection.on( 'close', function(){

			console.log('echo-protocol Connection Closed');
		} );

		connection.on( 'message', function( message ){

			if (message.type === 'utf8') {
				//console.log("Received: '" + message.utf8Data + "'");
				if ( message.utf8Data === '{"message":"test message"}' )
					deferred.resolve( true );
				else
					deferred.resolve( false );
			}
		} );

		function sendMessage(){

			if (connection.connected) {
	
				var obj = JSON.stringify( { serverfunction : 'loopBack', message : 'test message' } );
				connection.sendUTF( obj );
			}
		}
		sendMessage();

	} );

	client.connect('ws://localhost:8080/', 'echo-protocol');
	
	return deferred.promise;
}
Esempio n. 16
0
    constructor(config) {
        this.socket = new WebSocketClient();
        this.events = {};
        this.queue = [];
        this.mii = {};
        this.devices = {};

        this.socket.on('connect', this._handleConnect.bind(this));
        this.socket.on('connectFailed', this._handleError.bind(this));
        this.socket.connect(`ws://${config.host}:${config.port}/${config.password}`);
    }
 it('create with existing Node websocket', function(done) {
   var WebSocketClient = require('websocket').client;
   var client = new WebSocketClient();
   client.on('connectFailed', done);
   client.on('connect', function(webSocket) {
     var connection = new WebsocketConnection(webSocket);
     assert.isTrue(connection.isOpened());
     done();
   });
   client.connect(websocketServer.getAddress());
 });
var getConnection = function getConnection(id, callback) {
  console.log('Creando conexion' + id);
  var conn = new wsClient();
  conn.on('connectFailed', function(error) {
    console.log('Connect Error: ' + error.toString());
  });
  conn.on('connect', function(connection) {
    callback(id, connection);
  });
  conn.connect(WSADRESS, PROTOCOL);
};
 connect: function (regIds, messageHandler, done) {
     var socket = new WebSocket();
     socket.on("connect", function (conn) {
         conn.on("message", asyncExpect(function (data) {
             expect(data.type).to.eql("utf8");
             var msg = JSON.parse(data.utf8Data);
             messageHandler(msg);
         }, done, true)).sendUTF(JSON.stringify({ event: "addRegId", seq: 0, regIds: regIds }));
     }).connect(this.workerUrl, "msg-json");
     return socket;
 }
Esempio n. 20
0
exports.createClient = function (host, port, key, tenant, cb) {
  var wsclient = new WebSocketClient();
  wsclient.connect('wss://' + host + ':' + port + '/');
  wsclient.once('connectFailed', function (error) {
    cb(error);
  });
  wsclient.once('connect', function (channel) {
    var client = new exports.Client(channel, key, tenant);
    cb(null, client);
  });
};
Esempio n. 21
0
 it('should accept websocket connections', (done) => {
     var client = new WebSocketClient();
     client.connect("ws://localhost:"+global.config.port);
     client.on('connectFailed', (err) => {
         throw new Error(err);
     });  
     client.on('connect', (conn) => {
         conn.close();
         done();
     });
 });
request('https://slack.com/api/rtm.start?token='+process.env.SLACK_BOT_TOKEN, function(error, response) {
  const parsedData = JSON.parse(response.body);

  // Tell dashbot when you connect.
  dashbot.logConnect(parsedData);

  const bot = parsedData.self;
  const team = parsedData.team;
  client.on('connect', function(connection) {
    console.log('Slack bot ready');
    connection.on('message', function(message) {
      const parsedMessage = JSON.parse(message.utf8Data);

      // Tell dashbot when a message arrives
      dashbot.logIncoming(bot, team, parsedMessage);

      if (parsedMessage.type === 'message' && parsedMessage.channel &&
        parsedMessage.channel[0] === 'D' && parsedMessage.user !== bot.id) {
        if (parsedMessage.text.length%2 === 0) {
          // reply on the web socket.
          const reply = {
            type: 'message',
            text: 'You are right when you say: '+parsedMessage.text,
            channel: parsedMessage.channel
          };

          // Tell dashbot about your response
          dashbot.logOutgoing(bot, team, reply);

          connection.sendUTF(JSON.stringify(reply));
        } else {
          // reply using chat.postMessage
          const reply = {
            text: 'You are wrong when you say: '+parsedMessage.text,
            as_user: true,
            channel: parsedMessage.channel
          };

          // Tell dashbot about your response
          var id = dashbot.logOutgoing(bot, team, reply);

          request.post('https://slack.com/api/chat.postMessage?token='+process.env.SLACK_BOT_TOKEN,
            function (error, response) {
              // tell dashbot if there are errors.
              dashbot.logOutgoingResponse(id, error, response);
            }).form(reply);
        }
      }

    });
  });
  client.connect(parsedData.url);
});
        it('should reject clients that use malformed requests', function(done){
            var host = '0.0.0.0';
            var port = 61232;
            var server = new BootstrapServer(host, port);
            server.listen();
            var client = new WebSocketClient();
            client.on('connectFailed', function(errorDescription){
                server.close();
                done();
            });

            client.connect('ws://localhost:' + port + '/abc');
        });
        it('should listen on given port and let client connect', function(done){
            var host = '0.0.0.0';
            var port = 61232;
            var server = new BootstrapServer(host, port);
            server.listen();
            var client = new WebSocketClient();
            client.on('connect', function(){
                server.close();
                done();
            });

            client.connect('ws://localhost:' + port + '/ws/myid');
        });
Esempio n. 25
0
  registerUA: function registerUA() {
    var port = require('../../src/config.js').NS_UA_WS.interfaces[0].port;
    var WebSocketClient = require('websocket').client;
    var client = new WebSocketClient();

    client.on('connectFailed', function(error) {
      console.log('Connect Error: ' + error.toString());
    });

    client.on('connect', function(connection) {
      PushTest.connection = connection;
      debug('WebSocket client connected');
      connection.on('error', function(error) {
	console.log("Connection Error: " + error.toString());
      });
      connection.on('close', function() {
	debug('push-notification Connection Closed');
      });
      connection.on('message', function(message) {
	if (message.type === 'utf8') {
	  debug("Received: '" + message.utf8Data + "'");
	  var msg = JSON.parse(message.utf8Data);
	  debug(msg);
	  var notificationJSON = JSON.parse(PushTest.NOTIFICATION);
	  if (!Array.isArray(msg)) msg = [msg];
	  if (msg[0].status == 'REGISTERED' && msg[0].messageType == "registerUA") {
	    PushTest.registerUAOK = true;
	    debug("UA registered");
	  } else if (msg[0].status == 'REGISTERED' && msg[0].messageType == 'registerWA') {
	    PushTest.registerWAOK = true;
	    PushTest.url = msg[0].url;
	    debug("WA registered with url -- " + msg[0].url);
	  } else if (msg[0].messageType == 'notification') {
	    PushTest.gotNotification = true;
	    PushTest.connection.sendUTF('{"messageType": "ack", "messageId": "' + msg[0].messageId+ '"}');
	    debug("Notification received!! Sending ACK");
	  }
	}
      });

      function sendRegisterUAMessage() {
	if (connection.connected) {
	  var msg = ('{"data": {"uatoken":"' + PushTest.token + '"}, "messageType":"registerUA"}');
	  connection.sendUTF(msg.toString());
	  PushTest.registerUAOK = false;
	}
      }
      sendRegisterUAMessage();
    });
    client.connect('wss://' + PushTest.host + ':' + PushTest.port, 'push-notification');
  },
Esempio n. 26
0
        init: function init(cb) {
            if(ws){
                ws.close();
                ws = null;
            }
            ws = new WebSocketClient();
            ws.on('connect', function petifyConnectEvent(connection){
                bot.log("Connected to Petify");
                connection.sendUTF(JSON.stringify({type: "registerDevice", message: bot.config.petify.deviceID}));
                setTimeout(function(){
                    connection.sendUTF(JSON.stringify({type: "receiveSongUpdates", message: true}));
                    bot.log("Sent receiveSongUpdates Message")
                }, 1000);

                connection.on('message', function(message){
                    try {
                        var data = JSON.parse(message.utf8Data);

                        if (data.type === "songUpdate" && data.message.type === "play") {
                            bot.web_p.users.profile.set({
                                user: "******",
                                profile: JSON.stringify({
                                    status_text: "Now Playing: " + data.message.data.artist + " - " + data.message.data.title,
                                    status_emoji: ":petify:"
                                })
                            }, function(){
                                console.log(JSON.stringify(arguments));
                            });
                        }
                    }catch(e){
                        console.log(e);
                        bot.log("Fatrted");
                    }
                });

                connection.on('close', function petifyConnectClose(code){
                    bot.log("Connection closed - reconnecting "+code);
                    if(code !== 1000)
                        setInterval(object.init, 1000);
                });
                connection.on('error', function petifyConnectClose(err){
                    bot.log("Connection error - reconnecting "+err);
                    setInterval(object.init, 1000);
                });
            });
            bot.log("Connecting to Petify...");
            ws.connect("wss://unacceptableuse.com/petify/ws/updates/"+bot.config.petify.apiKey, null);
            cb();
        }
Esempio n. 27
0
    sendToWebSocket = function (data) {
        if (client.readyState === client.OPEN) {
			//console.log(convertToString(data));
            client.send(data);
            //connection.sendBytes(data);
        }
    }
Esempio n. 28
0
  io.on("handshake", function(addr) {
    var ws = new WebSocketClient();

    ws.on("connectFailed", function(error) {
      console.log("Connect Error: " + error.toString());
    });

    ws.on("connect", function(connection) {
      connection.on("error", function(error) {
        console.log("Connection Error: " + error.toString());
      });
      connection.on("close", function() {
        console.log("Connection closed");
      });
      connection.on("message", function(message) {
        try {
          io.message(message.utf8Data);
        } catch(e) {
          console.log(e);
        }
      });

      io.on("send", function(message) {
        connection.send(message);
      });

      var client = new gamenode.Client({crashOnError: true}, io, Manager);

      io.on("message", function(message) {
        try {
          client.handle(message);
        } catch(e) {
          console.log(e);
        }
      });

      //client.debug = true;
      client.onMethodListReceived = function() {
        callback(client);
      };

      client.sendMethodListRequest();
    });

    console.log("Connecting to: " + addr);
    ws.connect(addr);
  });
Esempio n. 29
0
 function open() {
   timeout = 0;
   close();
   metalog.warn('cube_emitter', {is: 'opening socket', url: url});
   var client = new websocket.client();
   client.on("connect", function(connection) {
     socket = connection;
     socket.on("message", log);
     socket.on("error", reopen);
     socket.on("close", reopen);
     flush();
     if (closing) closeWhenDone();
   });
   client.on("connectFailed", reopen);
   client.on("error", reopen);
   client.connect(url);
 }
Esempio n. 30
0
global.WebSocket = function(wsurl,protocol) {
    var ws = new WebSocketClient();
    var connection;
    var obj = {
        send: function(msg) {
            var nodeBuf = new Buffer(new Uint8Array(msg));
            connection.send(nodeBuf);
        },
        get readyState() { return ws.readyState; }
    };

    ws.binaryType = 'arraybuffer';

    ws.on("connect", function(conn) {
        connection = conn;
        conn.on("error", function (error) {
            console.log("socket error ",error);
            if (obj.onerror) {
                obj.onerror();
            }
        });

        conn.on("close", function(reasonCode, description) {
            console.log("socket closed ",description);
        })

        conn.on("message", function (message) {
            if (message.type === "binary") {
                if (obj.onmessage) {
                    obj.onmessage({data:message.binaryData});
                }
            }
        });
        if (obj.onopen) {
            obj.onopen();
        }
    });
    ws.on('connectFailed', function(error) {
        console.log('Connect Error: ' + error.toString());
        if (obj.onerror) {
            obj.onerror(error);
        }
    });
    ws.connect(wsurl, protocol);
    return obj;
}