Handle a connection event.

@param socket The underlying client socket.
@param server The TCP or UNIX server.
171313
function connection(socket, server) {
  var conn = new Connection(socket)
    , tcp = (server instanceof TcpServer);

  var maxclients = this.conf.get(ConfigKey.MAXCLIENTS);
  if(maxclients && (this.state.length + 1 > maxclients)) {

    this.state.emit('rejected', conn.client.addr, maxclients);

    this.log.debug('rejected %s, exceeds maxclients %s',
      conn.client.addr, maxclients);

    function onWrite() {
      socket.end();
    }

    return conn.write(MaxClients, onWrite.bind(this));
  }

  if(tcp) {
    this.log.debug('accepted connection from %s', conn.client.addr);
  }else if(server) {
    this.log.debug('accepted connection to %s', server.name);
  }else if(!server) {
    this.log.debug('accepted connection in %s', process.pid);
  }

  var timeout = this.conf.get(ConfigKey.TIMEOUT);
  if(typeof timeout === 'number' && timeout) {
    this.log.debug('setting idle timeout for client #%s to %ss',
      conn.id, timeout);
    // config is seconds, socket want milliseconds
    socket.setTimeout(timeout * 1000, function onTimeout() {
      // TODO: log client connection timeout
      socket.destroy();
    })
  }

  conn.once('disconnect', this.disconnect.bind(this));
  conn.on('command', this.command);
  this._state.addConnection(conn);
}
801498
private void loop(final ServerSocket server) throws IOException {
        try {
            this.back.accept(server.accept());
        } catch (final SocketTimeoutException ignored) {
        }
    }
973776
function _handleConnection(client) {
	client.on('message', curry(_handleMessage, client))
	client.on('disconnect', curry(_handleDisconnect, client))
	client.pubsub = _engine.getPubSub()
	_emitter.emit('client_connect', client)
}
73361
public void run() {

		try {
			while (true) {
				//server thread blocks until a client connects
				Socket socket = server.accept();

				System.out.println(new LogEntry("client (" + socket.getInetAddress().getHostAddress() + ") attempts to connect..."));
				Connection c = establishConnection(socket);
				updateConnectedClients(c);
			}
		} catch (IOException ioe) {
			System.out.println(new LogEntry("server forced to stop with message " + ioe.getClass().getName() + ' ' + ioe.getMessage()));
		} catch (Throwable t) {
			System.out.println(new LogEntry(Level.CRITICAL, "server forced to stop with message " + t.getClass().getName() + ' ' + t.getMessage(), t));
		}
	}
973854
protected void handleClient(final Socket client) throws IOException {
		final ClientHandler handler = new ClientHandler(client);
		this.executorService.execute(handler);
	}
1209432
protected function onIncoming(SocketServer $socket, Closure $callback): void
    {
        $socket->on('connection', function ($conn) use ($callback) {
            $conn->on('data', $callback);
        });
    }
1135749
def _handle_stream(self, stream, address):
        """"""
        try:
            assert get_thread_ident() == self.ioloop_thread_id
            stream.set_close_callback(partial(self._stream_closed_callback,
                                              stream))
            # Our message packets are small, don't delay sending them.
            stream.set_nodelay(True)
            stream.max_write_buffer_size = self.MAX_WRITE_BUFFER_SIZE

            # Abuse IOStream object slightly by adding 'address' and 'closing'
            # attributes. Use nasty prefix to prevent naming collisions.
            stream.KATCPServer_address = address
            # Flag to indicate that no more write should be accepted so that
            # we can flush the write buffer when closing a connection
            stream.KATCPServer_closing = False

            client_conn = self.client_connection_factory(self, stream)
            self._connections[stream] = client_conn
            try:
                yield gen.maybe_future(self._device.on_client_connect(client_conn))
            except Exception:
                # If on_client_connect fails there is no reason to continue
                # trying to handle this connection. Try and send exception info
                # to the client and disconnect
                e_type, e_value, trace = sys.exc_info()
                reason = "\n".join(traceback.format_exception(
                    e_type, e_value, trace, self._tb_limit))
                log_msg = 'Device error initialising connection {0}'.format(reason)
                self._logger.error(log_msg)
                stream.write(str(Message.inform('log', log_msg)))
                stream.close(exc_info=True)
            else:
                self._line_read_loop(stream, client_conn)
        except Exception:
            self._logger.error('Unhandled exception trying '
                               'to handle new connection', exc_info=True)
55300
@Override
    public void connect(String ip, int port)
    {
        network.connect(ip, port);
        for (final ConnectionListener listener : listeners)
        {
            network.addListener(listener);
        }
        network.addListener(this);
    }
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();
    }
  });
}
544958
public void setSocket(Socket socket) throws IOException {
        if (this.socket != null) {
            this.socket.close();
            this.socket = null;
        }
        this.socket = socket;
        setTimeout(timeout);
        prepareStreams(socket);
    }
543478
function NetworkServer(server) {
  this.server = server;
  function connection(socket) {
    server.connection(socket, this);
  }
  this.on('connection', connection);
}
700528
public function handleConnect($server, $socket)
    {
        $socket->conn = new NetworkConnection($socket);

        try
        {
            $this->component->handleConnect($socket->conn);

            $socket->on('data',  [ $this, 'handleData' ]);
            $socket->on('error', [ $this, 'handleError' ]);
            $socket->on('close', [ $this, 'handleDisconnect' ]);
        }
        catch (Error $ex)
        {
            $this->close($socket);
        }
        catch (Exception $ex)
        {
            $this->close($socket);
        }
    }
1061775
def streamserver_handle(cls, sock, address):
        ''''''
        request = cls.false_request()
        request._sock = sock
        server = None
        log.debug("Accepted connection, starting telnet session.")
        try:
            cls(request, address, server)
        except socket.error:
            pass
33321
function trigger(event, data) {
  // Warn if someone tries to trigger a message but the client socket
  // has already disconnected
  if (this.disconnected) {
    debug("Trying to trigger client socket but client is disconnected");
    return;
  }

  // If the broadcast flag is set, call to this.broadcast.send
  if (this.flags && this.flags.broadcast) {
    debug("Broadcasting %s to frontend clients, with data: %j.", event, data);
    this.broadcast.send({
      "event": event,
      "data": data
    });
  } else {
    debug("Triggering: %s on frontend with data: %j.", event, data);
    this.send({
      "event": event,
      "data": data
    });
  }
}
1066213
def handle(self):
        
        # self.request is the TCP socket connected to the client
        try:
            while not self.server._shutdown_request_event.is_set():
                try:
                    data = self.request.recv(8192)
                    if not data:
                        break
                    if self.debug:
                        self.log.debug("RECV: %r" % data)
                    self.buffer.append(data)

                    for frame in self.buffer:
                        self.log.debug("Processing frame: %s" % frame)
                        self.engine.process_frame(frame)
                        if not self.engine.connected:
                            raise ClientDisconnected()
                except socket.timeout:  # pragma: no cover
                    pass
        except ClientDisconnected:
            self.log.debug("Client disconnected, discontinuing read loop.")
        except Exception as e:  # pragma: no cover
            self.log.error("Error receiving data (unbinding): %s" % e)
            self.engine.unbind()
            raise
790447
def _handle_event(self, connection, event):
        
        with self.mutex:
            matching_handlers = sorted(
                self.handlers.get("all_events", [])
                + self.handlers.get(event.type, [])
            )
            for handler in matching_handlers:
                result = handler.callback(connection, event)
                if result == "NO MORE":
                    return
1258841
protected void runEchoService(ServerSocket serverSocket) {
    if (isRunning(serverSocket)) {

      echoService = newExecutorService();

      echoService.submit(() -> {
        try {
          while (isRunning(serverSocket)) {
            Socket echoClient = serverSocket.accept();

            getLogger().info(() -> String.format("EchoClient connected from [%s]",
              echoClient.getRemoteSocketAddress()));

            echoService.submit(() -> {
              sendResponse(echoClient, receiveMessage(echoClient));
              close(echoClient);
            });
          }
        }
        catch (IOException cause) {
          if (isRunning(serverSocket)) {
            getLogger().warning(() -> String.format("An IO error occurred while listening for EchoClients:%n%s",
              ThrowableUtils.getStackTrace(cause)));
          }
        }
      });

      getLogger().info(() -> String.format("EchoServer running on port [%d]", getPort()));
    }
  }