Handle a new socket connection.
434824
def websocket_handler(request):
    """"""

    logger.debug('New websocket connection.')
    websocket = web.WebSocketResponse()
    yield from websocket.prepare(request)
    uuid = uuid4()
    request.app['dispatcher'].subscribe(uuid, websocket)

    while True:
        # Consume input buffer
        try:
            msg = yield from websocket.receive()
        except RuntimeError as e:
            logger.debug('Websocket exception: %s', str(e))
            break
        except CancelledError:
            logger.debug('Websocket closed')
            break
        if msg.type == aiohttp.WSMsgType.CLOSED:
            logger.debug('Websocket closed')
            break
        elif msg.type == aiohttp.WSMsgType.ERROR:
            logger.debug('Websocket exception: %s', websocket.exception())
            break

    request.app['dispatcher'].unsubscribe(uuid)
    return websocket
400231
def add_socket(self, socket):
        
        if socket not in self._sockets:
            self._sockets.add(socket)
            socket.on_closed.connect(self.remove_socket)
306040
protected void handleConnection(Socket connection) throws IOException
    {
        if (log.isDebugEnabled()) log.debug("Handle " + connection);
        InputStream in = connection.getInputStream();
        OutputStream out = connection.getOutputStream();

        handleConnection(in, out);
        out.flush();

        in = null;
        out = null;
        connection.close();
    }
1235845
def new_conn(self):
        
        """
        :return:
        """
        logger.debug("Opening new connection to rethinkdb with args=%s" % self._conn_args)
        return ConnectionWrapper(self._pool, **self._conn_args)
30779
def handle(self, sock, read_data, path, headers):
        ""
        for i in range(self.attempts):
            try:
                server_sock = eventlet.connect(
                    tuple(random.choice(self.backends)),
                )
            except socket.error:
                eventlet.sleep(self.delay)
                continue
            # Function to help track data usage
            def send_onwards(data):
                server_sock.sendall(data)
                return len(data)
            try:
                size = send_onwards(read_data)
                size += SocketMelder(sock, server_sock).run()
            except socket.error, e:
                if e.errno != errno.EPIPE:
                    raise
1297421
def connect(self):
        """"""
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._socket.settimeout(self._connect_timeout)
        SocketError.wrap(self._socket.connect, (self.host, self.port))
        self._socket.settimeout(None)
        self._socket_file = self._socket.makefile('rb')
255358
public void processNewConnection(SocketIOChannel socket) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "processNewConnection");
        }

        VirtualConnection vc = vcf.createConnection();
        TCPConnLink bc = (TCPConnLink) tcpChannel.getConnectionLink(vc);
        TCPReadRequestContextImpl bcRead = bc.getTCPReadConnLink();

        bc.setSocketIOChannel(socket);

        ConnectionDescriptor cd = vc.getConnectionDescriptor();
        Socket s = socket.getSocket();
        InetAddress remote = s.getInetAddress();
        InetAddress local = s.getLocalAddress();

        if (cd != null) {
            cd.setAddrs(remote, local);
        } else {
            ConnectionDescriptorImpl cdi = new ConnectionDescriptorImpl(remote, local);

            vc.setConnectionDescriptor(cdi);
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Processing Connection: " + vc.getConnectionDescriptor());
        }

        int rc = vc.attemptToSetFileChannelCapable(VirtualConnection.FILE_CHANNEL_CAPABLE_ENABLED);
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "FileChannelCapable set in VC to: " + rc);
        }

        bcRead.setJITAllocateSize(bc.getConfig().getNewConnectionBufferSize());
        int timeout = bc.getConfig().getInactivityTimeout();
        if (timeout == ValidateUtils.INACTIVITY_TIMEOUT_NO_TIMEOUT) {
            timeout = TCPRequestContext.NO_TIMEOUT;
        }

        // Set a chain property that is used later by the SSL channel on Z only
        // (CRA)
        // This is needed to support a Z unique client certificate mapping function
        // which may be moved to non Z platforms in the future.
        vc.getStateMap().put("REMOTE_ADDRESS", bc.getRemoteAddress().getHostAddress());

        bcRead.read(1, cc, true, timeout);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "processNewConnection");
        }
    }
1371218
def dispatch_sockets(self, timeout=None):
        """"""
        for sock in self.select_sockets(timeout=timeout):
            if sock is self.listener:
                listener = sock
                sock, addr = listener.accept()
                self.connected(sock)
            else:
                try:
                    sock.recv(1)
                except socket.error as exc:
                    if exc.errno != ECONNRESET:
                        raise
                self.disconnected(sock)
743834
def connected_socket(address, timeout=3):
    
    sock = socket.create_connection(address, timeout)
    yield sock
    sock.close()
1027582
def handle_connection(socket)
      start_time = Time.now
      _, port, host = socket.peeraddr
      logger.debug("Client #{host}:#{port} connected")
      request = socket.read
      logger.debug("Received client request (#{request.length} bytes):\n" \
                   "#{request}")

      response = nil
      if request.to_s =~ /\ACONNECT ([_a-zA-Z0-9\.\-]+:[\d]+) .*$/
        host = $1.to_s
        logger.info("Negotiating connection to #{host}")
        response = send_request("GET http://#{host}/ HTTP/1.0\n\n")

        if response['code'].to_i == 502 || response['code'].to_i == 504
          logger.info("Connection to #{host} failed")
          socket.write("#{response['status_line']}\n" \
                       "#{response['headers']}\n" \
                       "#{response['body']}")
          raise Errno::ECONNRESET
        end

        logger.info("Connected to #{host} successfully")
        socket.write("HTTP/1.0 200 Connection established\r\n\r\n")
        request = socket.read
        logger.debug("Received client request (#{request.length} bytes):\n" \
                     "#{request}")

        # CHANGE_CIPHER_SPEC  20   0x14
        # ALERT               21   0x15
        # HANDSHAKE           22   0x16
        # APPLICATION_DATA    23   0x17
        if request.to_s.start_with?("\x14", "\x15", "\x16", "\x17")
          logger.warn("Received SSL/TLS client request. SSL/TLS tunneling is not supported. Aborted.")
          raise Errno::ECONNRESET
        end
      end

      response = send_request(request.to_s)
      socket.write("#{response['status_line']}\n" \
                   "#{response['headers']}\n" \
                   "#{response['body']}")
      raise Errno::ECONNRESET
    rescue EOFError, Errno::ECONNRESET, Errno::EPIPE
      socket.close
      logger.debug("Client #{host}:#{port} disconnected")
      end_time = Time.now
      duration = ((end_time - start_time) * 1000).round(3)
      if response.nil?
        logger.info("Served 0 bytes in #{duration} ms")
      else
        logger.info("Served #{response['body'].length} bytes in #{duration} ms")
      end
    end
1018050
def connect(self):
        """"""
        self.socket = socket.create_connection(self.address, self.timeout)
224085
def on_connect(self, connection):
        ""
        self._stream = connection._reader
        self._buffer = SocketBuffer(self._stream, self._read_size)
        if connection.decode_responses:
            self.encoding = connection.encoding
198885
protected void startOutgoingConnection (final Connection conn, InetSocketAddress addr)
    {
        final SocketChannel sockchan = conn.getChannel();
        try {
            // register our channel with the selector (if this fails, we abandon ship immediately)
            conn.selkey = sockchan.register(_selector, SelectionKey.OP_CONNECT);

            // start our connection process (now if we fail we need to clean things up)
            NetEventHandler handler;
            if (sockchan.connect(addr)) {
                _outConnValidator.validateOutgoing(sockchan); // may throw
                // it is possible even for a non-blocking socket to connect immediately, in which
                // case we stick the connection in as its event handler immediately
                handler = conn;

            } else {
                // otherwise we wire up a special event handler that will wait for our socket to
                // finish the connection process and then wire things up fully
                handler = new OutgoingConnectionHandler(conn);
            }
            _handlers.put(conn.selkey, handler);

        } catch (IOException ioe) {
            log.warning("Failed to initiate connection for " + sockchan + ".", ioe);
            conn.connectFailure(ioe); // nothing else to clean up
        }
    }
180386
@Override
    public void handle(final ServerWebSocket socket) {
        LOGGER.info("New web socket connection {}, {}", socket, socket.uri());

        if (! configuration.accept(socket.uri())) {
            LOGGER.warn("Web Socket connection denied on {} by {}", socket.uri(), configuration.name());
            return;
        }

        final Socket sock = new Socket(socket);
        accessor.getDispatcher().addSocket(socket.path(), sock);

        socket.closeHandler(event -> {
            LOGGER.info("Web Socket closed {}, {}", socket, socket.uri());
            accessor.getDispatcher().removeSocket(socket.path(), sock);
        });

        socket.handler(event -> accessor.getDispatcher().received(socket.path(), event.getBytes(), sock));

    }
1366223
def handle(self, sock, read_data, path, headers):
        ""
        assert self.type is not None
        try:
            # Get the correct file
            try:
                fh = open(os.path.join(self.balancer.static_dir, "%s.http" % self.type))
            except IOError:
                fh = open(os.path.join(os.path.dirname(__file__), "static", "%s.http" % self.type))
            # Send it, using sendfile if poss. (no fileno() means we're probably using mock sockets)
            try:
                self._sendfile(sock.fileno(), fh.fileno(), 0, os.fstat(fh.fileno()).st_size)
            except (TypeError, AttributeError):
                sock.sendall(fh.read())
            # Close the file and socket
            fh.close()
            sock.close()
        except socket.error, e:
            if e.errno != errno.EPIPE:
                raise
790808
def _accept(self, listen_socket):
        
        conn, addr = listen_socket.accept()
        connection = TelnetConnection(conn, addr, self.application, self, encoding=self.encoding)
        self.connections.add(connection)

        logger.info('New connection %r %r', *addr)
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);
}