Establishes a socket connection to the zombie.js server and sends
        Javascript instructions.

        :param js: the Javascript string to execute
344129
def _send(self, javascript):
        

        # Prepend JS to switch to the proper client context.
        message = """
            var _ctx = ctx_switch('%s'),
                browser = _ctx[0],
                ELEMENTS = _ctx[1];
            %s
        """ % (id(self), javascript)

        response = self.connection.send(message)

        return self._handle_response(response)
1112765
function join() {
  // import all in lib/js/, called only when the modules are needed
  lib_js = requireDir(path.join(__dirname, 'js'))
  log.debug(`import js lib from client.js`)
  const IOPORT = process.env.IOPORT || 6466
  log.info(`Starting socketIO client for js at ${IOPORT}`)
  client = socketIOClient(`http://localhost:${IOPORT}`)
  client.emit('join', ioid)
  client.on('disconnect', client.disconnect)
  client.on('take', handle)
  return client
}
949886
function startServer(alerts, params, port, resources) {
    const compiledAlerts = compileMarkdown(alerts);
    const app = http.createServer((req, res) =>
        res.end(resources[req.url] || resources['/index.html']));
    const io = listen(app);
    io.on('connection', socket => {
        emitInfo(`new session for ${socket.handshake.address}`);
        socket.emit('update', compiledAlerts);
        socket.on('disconnect', () => {
            emitInfo(`disconnected session ${socket.handshake.address}`);
        });
    });

    return new Promise(resolve => app.listen(port, emitRungEmoji & resolve))
        .then(~watchChanges(io, params));
}
565210
function() {
        try {
          var server = {
            "host": params.host,
            "port": params.port,
            "timeout": params.timeout || 20000,
            "connectHeaders": {
              "host": "/",
              "login": params.username,
              "passcode": params.password,
              "heart-beat": "5000, 5000"
            }
          };

          var servers = [server];

          var reconnectOptions = {
            'maxReconnects': 20
          };

          var manager = new Stompit.ConnectFailover(servers, reconnectOptions);

          manager.connect(function(error, stompClient, reconnect) {
            if (error) {
              fireEvent("error", {
                errorCode: error.code,
                errorMessage: error.message,
                errorEvent: error
              });

              return;
            }

            client = stompClient;

            client.on('error', function(error) {
              fireEvent("error", {
                errorCode: 999,
                errorMessage: "ActiveMQ client has had an error",
                errorEvent: error
              });
              reconnect();
            });

            fireEvent("init");
          });

        } catch (error) {
          console.error(error);
        }
      }
171360
function wsConnect() {

            var typeOfConnection;

            if (location.protocol === 'https:') {
                typeOfConnection = 'wss';
            } else {
                typeOfConnection = 'ws'
            }

            self.ws = new WebSocket(typeOfConnection + '://' + location.hostname + ':' + location.port);

            self.ws.onopen = function (event) {

                //send an intial message to server and prove that the connection is built.
                self.send('connected', 'WSM: Browser confirms websocket connection.')

                reactive(self);

            };

            self.ws.onmessage = function (event) {
                // flags.binary will be set if a binary data is received.
                // flags.masked will be set if the data was masked.
                //console.log(event.data);

                self.processMessage(JSON.parse(event.data));
            };

            self.ws.onclose = function (event) {

                wsConnect();
            }
        }
1241424
function connection(socket){
	this.socket = socket;
	if (!!this.options.encoding) socket.setEncoding(this.options.encoding);
	socket.on('data', this.emit.bind(this, 'data'));
	this.emit('connection', socket);
}
288821
function Connector(src, onconnect) {
  events.EventEmitter.call(this);

  this.src = src;

  this.once('result', function (err, socket) {
    socket.removeAllListeners('error');
    if (err) {
      this.emit('prefailed', err);
      this.emit('failed', err);
    } else {
      this.emit('preready', socket);
      this.emit('ready', socket);
    }
  }).on('ready', function (socket) {
    onconnect(socket);
  }).on('failed', function (err) {
    src.emit('error', err);
  });
}
1054233
function() {

		var appConfig; // socket closure
		var isLoaded = false;
		// its possible for messages to be received before the socket load event has
		// happened.  We'll save off these messages and replay them once the socket
		// is ready
		var messagePlayback = [];

		var socket = new easyXDM.Socket({
			onMessage: function(message, origin){

				// handle Socket Load
				if (!isLoaded && _rSocketLoad.test(message)) {
					message = message.replace(_rSocketLoad, '');
					var appParts = F2.parse(message);

					// make sure we have the AppConfig and AppManifest
					if (appParts.length == 2) {
						appConfig = appParts[0];

						// save socket
						_apps[appConfig.instanceId] = {
							config:appConfig,
							socket:socket
						};	

						// register app
						F2.registerApps([appConfig], [appParts[1]]);

						// socket message playback
						jQuery.each(messagePlayback, function(i, e) {
							_onMessage(appConfig, message, origin);
						});
						
						isLoaded = true;
					}
				} else if (isLoaded) {
					// pass everyting else to _onMessage
					_onMessage(appConfig, message, origin);
				} else {
					//F2.log('socket not ready, queuing message', message);
					messagePlayback.push(message);
				}
			}
		});
	}
1014152
function() {
    var self = this;
    // Unfortunately we can't use a connect middleware here since
    // sockjs installs itself prior to all existing listeners
    // (meaning prior to any connect middlewares) so we need to take
    // an approach similar to overshadowListeners in
    // https://github.com/sockjs/sockjs-node/blob/cf820c55af6a9953e16558555a31decea554f70e/src/utils.coffee
    _.each(['request', 'upgrade'], function(event) {
      var httpServer = WebApp.httpServer;
      var oldHttpServerListeners = httpServer.listeners(event).slice(0);
      httpServer.removeAllListeners(event);

      // request and upgrade have different arguments passed but
      // we only care about the first one which is always request
      var newListener = function(request /*, moreArguments */) {
        // Store arguments for use within the closure below
        var args = arguments;

        // Rewrite /websocket and /websocket/ urls to /sockjs/websocket while
        // preserving query string.
        var parsedUrl = url.parse(request.url);
        if (parsedUrl.pathname === pathPrefix + '/websocket' ||
            parsedUrl.pathname === pathPrefix + '/websocket/') {
          parsedUrl.pathname = self.prefix + '/websocket';
          request.url = url.format(parsedUrl);
        }
        _.each(oldHttpServerListeners, function(oldListener) {
          oldListener.apply(httpServer, args);
        });
      };
      httpServer.addListener(event, newListener);
    });
  }
120353
function SocketClient (socket) {
    var that = this;

    this.socket = socket;
    this.socket_closing = false;

    this.remoteAddress = this.socket.remoteAddress;
    winston.info('Control connection from %s opened', this.socket.remoteAddress);

    this.bindEvents();

    socket.write("\nHello, you are connected to the Kiwi server :)\n\n");

    this.control_interface = new ControlInterface(socket);
    _.each(socket_commands, function(fn, command_name) {
        that.control_interface.addCommand(command_name, fn.bind(that));
    });
}
1086642
function (server_type, socket_url, connHandler, onDone) {

		// handles when connection with server is established
		var onConnect = function () {
			
			if (typeof connHandler === 'function')
				connHandler('connect');
			
			SR.Log('websocket server connected: ' + socket_url);
			if (typeof onDone === 'function')
				onDone();
		}
		
		// disconnect event
		var onDisconnect = function (obj) {
			if (typeof connHandler === 'function')
				connHandler('disconnect');
			
			SR.Warn('disconnected... obj: ');
			SR.Warn(obj);
			
			// attempt to re-connect
			if (typeof conn_options === 'object') {
				removeEntry(currentEntry);
				currentEntry = undefined;
				SR.Warn('re-connecting websocket with options');
				SR.Warn(conn_options);
				SR.setSocketServer(conn_options);
			}
		}
		
		// configure priority of protocol used
		//io.configure(function () { 
			//io.set("transports", ["xhr-polling", "flashsocket", "json-polling"]); 
		//});
				
		// connect to server
		SR.Log('connecting to server: ' + socket_url);
            
		if (server_type === 'socketio') {
            
			socket = io.connect(
				socket_url
				/*
				{	
					'reconnection delay': 10000,
					'reconnection limit': 4,
     	 			'max reconnection attempts': 4
				}
				*/
			);
			
			var generateHandler = function (name) {
				return function () {
					if (typeof connHandler === 'function')
						connHandler(name);
				}
			}
			
			// Return socket connection status and response
			for (var i=0; i < socketEvents.length; i++) {
				var event_name = socketEvents[i];
				socket.on(event_name, generateHandler(event_name));
			}
			
            // connection success
            socket.on('connect', onConnect);
			socket.on('disconnect', onDisconnect);
			
			// move this outside of 'connect' event handling (to avoid duplicates)
			socket.on('SRR', function (data) {
				SR.Log('SRR received, type: ' + data[HEADER_UPDATE]);
				onResponse(data[HEADER_UPDATE], data[HEADER_PARA]);
			});
            
            // attach customized send function
            socket.sendJSON = function (obj) {
                socket.emit('SR', obj);
            }
		}
		else if (server_type === 'sockjs') {
			socket = {};
			var url = socket_url + '/sockjs';
			SR.Log('sockjs URL to connect: ' + url);

            // Create a connection to server
            var sock = new SockJS(url);
    
            // Open the connection
			sock.onopen = function () {
				socket.opened = true;
				// send cookie explicitly
				SR.Warn('sockjs sending cookie:');
				SR.Warn(document.cookie);
				sock.send(document.cookie);
				onConnect();
			}
			
            // On connection close
            sock.onclose = onDisconnect;

            // On receive message from server
            sock.onmessage = function (e) {
                // Get the content
                var obj = JSON.parse(e.data);
				onResponse(obj[HEADER_UPDATE], obj[HEADER_PARA]);
            }
            
            // attach customized send function
			
			socket.sendJSON = function (obj) {
								sock.send(JSON.stringify(obj));
            				};
		}
		else  {
			SR.Error('unrecongizable server_type: ' + server_type + ' please check if socket.io or sockjs is used');	
		}
	}
819535
def connect(self, server, port=6667):
        
        self.socket.connect((server, port))
        self.lines = self._read_lines()
        for event_handler in list(self.on_connect):
            event_handler(self)
1083028
async def send_script(self, conn_id, data):
        

        progress_callback = functools.partial(_on_progress, self, 'script', conn_id)

        resp = await self._execute(self._adapter.send_script_sync, conn_id, data, progress_callback)
        _raise_error(conn_id, 'send_rpc', resp)
1031371
function update() {
	connection = new Connection(room)
	// set our funcitonal code on the ready event, so we are sure that the socket has been created and is connected to the server
	connection.on('ready', _ => {
		connection.on('snapshot-event', event => {
			// get every listener including bots and lurkers
			userList = event.data.listing.sort()
			render(userList)
			connection.close()
		})
	})
}
1201333
async def send_script(self, conn_id, data):
        

        self._ensure_connection(conn_id, True)
        connection_string = self._get_property(conn_id, "connection_string")

        msg = dict(connection_string=connection_string, fragment_count=1, fragment_index=0,
                   script=base64.b64encode(data))
        await self._send_command(OPERATIONS.SEND_SCRIPT, msg, COMMANDS.SendScriptResponse)
1307741
function Server(server, options)
{
	events.EventEmitter.call(this);
	
	this.listen = function(options, callback) {
		server.listen(options, callback);
	};
	
	server.on('connection', (socket) => {
		options = options || {};
		options.isServer = true;
		this.emit('client', new Client(socket, options));
	});
}
420021
function WebsocketConnection(socket, url) {
  this.socket = socket;
  this.url = url;

  this.deferreds = {};
  this.nextRequestId = 0;

  this.onReply = this.onReply.bind(this);
  this.onEvent = this.onEvent.bind(this);
}