Handles communication with an interchange client over a socket.

Routes socket messages to the service's commandRouter.
170992
function _handleConnection(service, socket) {
  debug('New socket %s from %s', socket.id, socket.conn.remoteAddress);

  var remoteAddress = socket.conn.remoteAddress;

  eyes.inc('sockets.open');

  var context = {};

  context.db = service.db;
  context.hubClient = service.hubClient;

  context.setSessionId = function(sessionId) {
    context.sessionId = sessionId;
    service.setSessionSocket(sessionId, socket);
  }

  context.unsetSessionId = function() {
    if (!context.sessionId) {
      return;
    }
    service.clearSessionSocket(context.sessionId, socket);
    context.sessionId = null;
  }

  /**
   * Pushes a message to connected interchange clients who are following the
   * given targets.
   */
  context.targetCast = service.targetCast;

  /**
   * Handles the VOX command.  A VOX command wraps a URL, HTTP method, and JSON
   * data payload, and it expects a JSON response.
   *
   * @param method {String} The command's HTTP-like method.  E.g. "POST".
   * @param data.url {String} The URL of the command.  E.g.,
   *     "vox://<source>/threads/<threadId>".
   * @param data.payload {Object} The command's JSON payload.
   */
  function handleSocketMessage(method, data, replyFn) {
    debug('%s %s %s', socket.id, method, data.url, data.payload);
    eyes.mark('sockets.' + method);
    var url = data.url;
    if (!url) {
      replyFn({ status: 400, message: 'No URL given in request!' });
      return;
    }
    if (url.indexOf('/') == -1) {
      url += '/';  // Ensure that the URL can be routed.
    }
    var req = {
        context: context,
        method: method,
        url: url,
        remoteAddress: remoteAddress,
        payload: data.payload
    };
    if (!req.payload) {
      req.payload = {};
    }
    var replied = false;
    var res = {
        json: function(reply) {
          replyFn(reply);
          replied = true;
          debug('%s reply %s %s', socket.id, method, data.url);
          eyes.mark('sockets.' + method + '.status.200');
        },
        sendStatus: function(statusCode, message) {
          replyFn({ status: statusCode, message: message });
          replied = true;
          debug('%s reply %s %s', socket.id, method, data.url, statusCode);
          eyes.mark('sockets.' + method + '.status.' + statusCode);
        }
    };
    service.commandRouter.handle(req, res, function(err) {
      if (err) {
        console.error('Error handling %s %s:', method, data.url, err, err.stack);
        if (!replied) {
          console.error('No reply sent for %s %s...sending 500 error.', method, data.url);
          res.sendStatus(500, 'Server error');
        }
      } else if (!replied) {
        debug('No route found for %s %s...sending 404', method, data.url);
        res.sendStatus(404, 'Not found: ' + data.url);
      }
    });
  }

  socket.on('GET', handleSocketMessage.bind(null, 'GET'));
  socket.on('POST', handleSocketMessage.bind(null, 'POST'));
  socket.on('SUBSCRIBE', handleSocketMessage.bind(null, 'SUBSCRIBE'));
  socket.on('UNSUBSCRIBE', handleSocketMessage.bind(null, 'UNSUBSCRIBE'));

  socket.on('disconnect', function(data) {
    debug('DISCONNECT %s', context.sessionId);
    eyes.dec('sockets.open');
    if (context.sessionId) {
      var now = Date.now();
      context.db.setSessionConnected({
          sessionId: context.sessionId,
          isConnected: false,
          lastSeenAt: now
      });
      // TODO Handle errors.
      context.unsetSessionId();
    }
  });
}
426233
function Client(socket, options) {
  options = options || {};

  // hook up subcommand nested properties
  var cmd, sub, method;
  for(cmd in SubCommand) {
    // we have defined the cluster slots subcommand
    // but the cluster command is not returned in the
    // command list, ignore this for the moment
    if(!this[cmd]) continue;

    // must re-define the command method
    // so it is not shared across client instances
    method = this[cmd] = this[cmd].bind(this);

    function subcommand(cmd, sub) {
      var args = [].slice.call(arguments, 1), cb;
      if(typeof args[args.length - 1] === 'function') {
        cb = args.pop();
      }
      this.execute(cmd, args, cb);
      return this;
    }


    for(sub in SubCommand[cmd]) {
      method[sub] = subcommand.bind(this, cmd, sub);
    }
  }

  this.socket = socket;
  this.socket.on('connect', this._connect.bind(this));
  this.socket.on('data', this._data.bind(this));
  this.socket.on('error', this._error.bind(this));
  this.socket.on('close', this._close.bind(this));
  this.tcp = (this.socket instanceof Socket);

  // using a tcp socket connection
  if(this.tcp) {
    this.encoder = new Encoder(
      {return_buffers: options.buffers});
    this.encoder.pipe(this.socket);
    this.decoder = new Decoder(
      {
        simple: options.simple,
        return_buffers: options.buffers,
        raw: options.raw
      });
    this.decoder.on('reply', this._reply.bind(this))
  }
}
155750
public void handleConnection(Socket socket) throws IOException
    {
        // Check acceptable remote servers
        if (_remoteServers!=null&&_remoteServers.length>0)
        {
            boolean match=false;
            InetAddress inetAddress=socket.getInetAddress();
            String hostAddr=inetAddress.getHostAddress();
            String hostName=inetAddress.getHostName();
            for (int i=0; i<_remoteServers.length; i++)
            {
                if (hostName.equals(_remoteServers[i])||hostAddr.equals(_remoteServers[i]))
                {
                    match=true;
                    break;
                }
            }
            if (!match)
            {
                log.warn("AJP13 Connection from un-approved host: "+inetAddress);
                return;
            }
        }

        // Handle the connection
        socket.setTcpNoDelay(true);
        socket.setSoTimeout(getMaxIdleTimeMs());
        AJP13Connection connection=createConnection(socket);
        try
        {
            connection.handle();
        }
        finally
        {
            connection.destroy();
        }
    }
549014
def send_command(self, command):
        
        logger.debug("Connecting to socket %s", self.socket_file_path)
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        try:
            sock.connect(self.socket_file_path)
        except IOError as e:
            if e.errno == errno.ECONNREFUSED:
                logger.error("Connection refused.  Is HAProxy running?")
                return
            else:
                raise

        sock.sendall((command + "\n").encode())

        response = b""
        while True:
            try:
                chunk = sock.recv(SOCKET_BUFFER_SIZE)
                if chunk:
                    response += chunk
                else:
                    break
            except IOError as e:
                if e.errno not in (errno.EAGAIN, errno.EINTR):
                    raise

        sock.close()

        return self.process_command_response(command, response)
395676
function handleConnection(client) {
        // set ghostmode callbacks
        if (bs.options.get("ghostMode")) {
            addGhostMode(client);
        }

        client.emit("connection", bs.options.toJS()); //todo - trim the amount of options sent to clients

        emitter.emit("client:connected", {
            ua: client.handshake.headers["user-agent"]
        });
    }
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));
    });
}
437480
function sendMessage(client, to, message, callback) {
	resolveID(client, to, function(channelID) {
		client._req('post', Endpoints.MESSAGES(channelID), message, function(err, res) {
			handleResCB("Unable to send messages", err, res, callback);
		});
	});
}
459471
def handle(self):
        
        pid, fd = pty.fork()
        if pid:
            protocol = TelnetServerProtocolHandler(self.request, fd)
            protocol.handle()
        else:
            self.execute()
589084
function handleConnection(self, options) {
	if (TRACE)	console.log('Connected to ' + options.host + ':' + options.port)
    	//self.socket = socket;
	self.emit("connect");
}
260204
def send(self, cmd, *payload):
        

        # If it's closed, raise an error up front
        if not self._sock:
            raise ConnectionClosed("Connection closed")

        # Construct the outgoing message
        msg = json.dumps(dict(cmd=cmd, payload=payload)) + '\n'

        # Send it
        try:
            self._sock.sendall(msg)
        except socket.error:
            # We'll need to re-raise
            e_type, e_value, e_tb = sys.exc_info()

            # Make sure the socket is closed
            self.close()

            # Re-raise
            raise e_type, e_value, e_tb
270051
function controlChannelRequest(server, message) {
  var address = message.request.address;
  var req = { headers: {} };
  var headers = [];

  // handler to call when the connection sequence completes
  var self = server;
  
  if ( message.request.method) {
    req = new IncomingMessage(message, server.controlChannel);
    if ( message.request.body == true) {
       self.pendingRequest = req;
    } else {
      req.push(null);
    }
  }
  
  // execute the web socket rendezvous with the server
  try {
    var client = new WebSocket(address, {
      headers: headers,
      perMessageDeflate: false
    });
    client.on('open', function() {
      
      server.emit('requestchannel', client);
      if (self.options.clientTracking) {
        self.clients.push(client);
        ws.on('close', function() {
          var index = self.clients.indexOf(client);
          if (index != -1) {
            self.clients.splice(index, 1);
          }
        });
      }

      // do we have a request or is this just rendezvous?
      if ( message.request.method) {
         var res = new ServerResponse(req);
         res.requestId = message.request.id;
         res.assignSocket(client);
         server.emit('request', req, res);
      }
    });

    client.on('error', function(event) {
      var index = server.clients.indexOf(client);
      if (index != -1) {
        server.clients.splice(index, 1);
      }
    });

  } catch (err) {
    console.log(err);
  }
}
1089469
@Draft
    public static void recvMsg(ZMQ.Socket socket, int flags, Consumer<ZMsg> handler)
    {
        handler.accept(ZMsg.recvMsg(socket, flags));
    }
450286
def handle(self, sock, read_data, path, headers):
        ""
        if "://" not in self.redirect_to:
            destination = "http%s://%s" % (
                "s" if headers.get('X-Forwarded-Protocol', headers.get('X-Forwarded-Proto', "")).lower() in ("https", "ssl") else "",
                self.redirect_to
            )
        else:
            destination = self.redirect_to
        try:
            sock.sendall("HTTP/1.0 302 Found\r\nLocation: %s/%s\r\n\r\n" % (
                destination.rstrip("/"),
                path.lstrip("/"),
            ))
        except socket.error, e:
            if e.errno != errno.EPIPE:
                raise
90050
def _traceroute_callback(self, line, kill_switch):
    

    line = line.lower()
    if "traceroute to" in line:
        self.started = True
    # need to run as root but not running as root.
    # usually happens when doing TCP and ICMP traceroute.
    if "enough privileges" in line:
        self.error = True
        self.kill_switch()
        self.stopped = True
    # name resolution failed
    if "service not known" in line:
        self.error = True
        self.kill_switch()
        self.stopped = True
1344224
def handle_request(self):
        
        try:
            request, client_address = self.get_request()
        except socket.error:
            return
        if self.verify_request(request, client_address):
            try:
                # we only serve once, and we want to free up the port
                # for future serves.
                self.socket.close()
                self.process_request(request, client_address)
            except SocketConnected as err:
                self._serve_process(err.slaveFd, err.serverPid)
                return
            except Exception as err:
                self.handle_error(request, client_address)
                self.close_request()
523387
def streamserver_handle(cls, socket, address):
        ''''''
        request = cls.dummy_request()
        request._sock = socket
        server = None
        cls(request, address, server)
38962
def handle(conn, addr, gateway, *args, **kwargs):
    
    conn.sendall(b'OK pubsub 1.0\n')
    while True:
        try:
            s = conn.recv(1024).decode('utf-8').strip()
            if not s:
                conn.close()
                break
        except ConnectionResetError:
            logger.debug('Client close the connection.')
            break

        parts = s.split(' ')
        if len(parts) != 2:
            conn.send(b"Invalid command\n")
            continue
        cmd, topic = parts
        if cmd.lower() != 'sub':
            conn.send(bytes("Unknown command '{}'\n".format(cmd.lower()), 'utf-8'))
            continue
        if topic not in gateway.topics:
            conn.send(bytes("Unknown topic '{}'\n".format(topic), 'utf-8'))
            continue
        conn.sendall(bytes('ACK {} {}\n'.format(cmd, topic), 'utf-8'))
        subscriber = Subscriber(addr, conn)
        gateway.link(topic, subscriber)
        break