Accept a connection. The socket must be bound to an address
        and listening for connections. The return value is a new
        socket object usable to send and receive data on the
        connection.
966900
def accept(self):
        """"""
        socket = Socket(self._llc, None)
        socket._tco = self.llc.accept(self._tco)
        return socket
1083659
def accept(self):
        
        while 1:
            try:
                sock, addr = self._sock.accept()
                return (type(self)(sock,
                    keyfile=self.keyfile,
                    certfile=self.certfile,
                    server_side=True,
                    cert_reqs=self.cert_reqs,
                    ssl_version=self.ssl_version,
                    ca_certs=self.ca_certs,
                    do_handshake_on_connect=self.do_handshake_on_connect,
                    suppress_ragged_eofs=self.suppress_ragged_eofs,
                    ciphers=self.ciphers), addr)
            except socket.error, exc:
                if exc.args[0] not in (errno.EAGAIN, errno.EWOULDBLOCK):
                    raise
                sys.exc_clear()
                self._wait_event(self.gettimeout())
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
955697
def _send(self, ip, port, data):
        
        return self._listen_socket.sendto(data, (ip, port))
203847
def _socketpair_compat():
    """"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("127.0.0.1", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2)
766674
def _mainthread_accept_clients(self):
        
        try:
            if self._accept_selector.select(timeout=self.block_time):
                client = self._server_socket.accept()
                logging.info('Client connected: {}'.format(client[1]))

                self._threads_limiter.start_thread(target=self._subthread_handle_accepted,
                                                   args=(client,))
        except socket.error:
            pass
314003
def _init_listen_socket(self):
        
        self.debug("()")
        self._listen_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._listen_socket.setsockopt(
            socket.SOL_SOCKET,
            socket.SO_REUSEADDR,
            1
        )
        self._listen_socket.bind((self._listen_ip, self._listen_port))
        self._listening.append(self._listen_socket)
1324741
def attempt_connection(self):
        
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)

        self.receiver_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.receiver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.receiver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        self.receiver_socket.bind(('', MCAST_PORT))
        mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
        self.receiver_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        if not self.socket or not self.receiver_socket:
            raise exception.ConnectFailedException()
743834
def connected_socket(address, timeout=3):
    
    sock = socket.create_connection(address, timeout)
    yield sock
    sock.close()
761519
private boolean open() throws IOException
    {
        assert (fd == null);

        //  Resolve the address
        if (addr == null) {
            throw new IOException("Null address");
        }

        addr.resolve(options.ipv6);

        Address.IZAddress resolved = addr.resolved();
        if (resolved == null) {
            throw new IOException("Address not resolved");
        }

        SocketAddress sa = resolved.address();
        if (sa == null) {
            throw new IOException("Socket address not resolved");
        }

        //  Create the socket.
        if (options.selectorChooser == null) {
            fd = SocketChannel.open();
        }
        else {
            fd = options.selectorChooser.choose(resolved, options).openSocketChannel();
        }

        // On some systems, IPv4 mapping in IPv6 sockets is disabled by default.
        // Switch it on in such cases.
        // The method enableIpv4Mapping is empty. Still to be written
        if (resolved.family() == StandardProtocolFamily.INET6) {
            TcpUtils.enableIpv4Mapping(fd);
        }

        // Set the socket to non-blocking mode so that we get async connect().
        TcpUtils.unblockSocket(fd);

        //  Set the socket buffer limits for the underlying socket.
        if (options.sndbuf != 0) {
            TcpUtils.setTcpSendBuffer(fd, options.sndbuf);
        }
        if (options.rcvbuf != 0) {
            TcpUtils.setTcpReceiveBuffer(fd, options.rcvbuf);
        }

        // Set the IP Type-Of-Service priority for this socket
        if (options.tos != 0) {
            TcpUtils.setIpTypeOfService(fd, options.tos);
        }

        // TODO V4 Set a source address for conversations
        if (resolved.sourceAddress() != null) {
            //            SocketChannel bind = channel.bind(resolved.sourceAddress());
            //            if (bind == null) {
            //                return false;
            //            }
        }

        //  Connect to the remote peer.
        boolean rc;
        try {
            rc = fd.connect(sa);
            if (rc) {
                //  Connect was successful immediately.
            }
            else {
                //  Translate error codes indicating asynchronous connect has been
                //  launched to a uniform EINPROGRESS.
                errno.set(ZError.EINPROGRESS);
            }
        }
        catch (IllegalArgumentException e) {
            // this will happen if sa is bad.  Address validation is not documented but
            // I've found that IAE is thrown in openjdk as well as on android.
            throw new IOException(e.getMessage(), e);
        }

        return rc;

    }
840264
def _accept_loop(self):
        """"""
        self._listening_sock.setblocking(0)
        while not self._stopped and not _shutting_down:
            try:
                # Wait a short time to accept.
                if select.select([self._listening_sock.fileno()], [], [], 1):
                    client, client_addr = self._listening_sock.accept()
                    client.setblocking(True)
                    self._log('connection from %s' % format_addr(client_addr))
                    server_thread = threading.Thread(
                        target=functools.partial(
                            self._server_loop, client, client_addr))

                    # Store weakrefs to the thread and socket, so we can
                    # dispose them in stop().
                    self._server_threads[server_thread] = None
                    self._server_socks[client] = None

                    server_thread.daemon = True
                    server_thread.start()
            except socket.error as error:
                if error.errno not in (
                    errno.EAGAIN, errno.EBADF, errno.EWOULDBLOCK):
                    raise
            except select.error as error:
                if error.args[0] == errno.EBADF:
                    # Closed.
                    break
                else:
                    raise
1012943
def get_socket(self, address, role):
        
        #
        # If this thread doesn't yet have a sockets cache
        # in its local storage, create one here.
        #
        try:
            self._tls.sockets
        except AttributeError:
            self._tls.sockets = {}
        
        # Convert the address to a single canonical string.
        #
        # If a list of addresses is passed, turn it into a tuple
        # of canonical addresses for use as a dictionary key. 
        # Otherwise convert it to a single canonical string.
        #
        if isinstance(address, list):
            caddress = tuple(core.address(a) for a in address)
        else:
            caddress = core.address(address)
            
        #
        # Each socket is identified for this thread by its address(es)
        # and the role the socket is playing (listener, publisher, etc.)
        # That is, within one thread, we are cacheing a read or a write
        # socket to the same address(es).
        #
        # The slight corner case from this is that if you attempt to
        # send to [addressA, addressB] and then to addressA and then
        # to [addressB, addressA], three separate sockets will be
        # created and used.
        #
        identifier = caddress
        
        if identifier not in self._tls.sockets:
            _logger.debug("%s does not exist in local sockets", identifier)
            #
            # If this is a listening / subscribing socket, it can only
            # be bound once, regardless of thread. Therefore keep a
            # threads-global list of addresses used and make sure this
            # one hasn't been used elsewhere.
            #
            if role in Socket.binding_roles:
                with self._lock:
                    if identifier in self._sockets:
                        raise core.SocketAlreadyExistsError("You cannot create a listening socket in more than one thread")
                    else:
                        self._sockets.add(identifier)
            
            type = self.roles[role]
            socket = context.socket(type)
            socket.role = role
            socket.address = caddress
            #
            # Do this last so that an exception earlier will result
            # in the socket not being cached
            #
            self._tls.sockets[identifier] = socket
        else:
            _logger.debug("%s already not exist in local sockets", identifier)
            #
            # Only return sockets created in this thread
            #
            socket = self._tls.sockets[identifier]

        return socket
831977
def send(self, request):
        
        self._logger.debug('Opening connection')
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.connect((self._host, self._port))
        talk = SocketTalk(sock, encode=self._encode)

        self._logger.debug('Sending action %s' % request.action)
        if not talk.put(request.action):
            self._logger.error('Failed to send action %s' % request.action)
            return None

        if request.key is not None:
            self._logger.debug('Sending key %s' % request.key)
            if not talk.put(request.key):
                self._logger.error('Failed to send key %s' % request.key)
                return None

        if request.value is not None:
            self._logger.debug('Sending value')
            if not talk.put(request.value):
                self._logger.error('Failed to send value')
                return None

        self._logger.debug('Receiving status')
        response = talk.get()
        if not response:
            self._logger.error('Failed to receive status')
            return None
        self._logger.debug('Status response = %s' % response)

        if request.action in ('get', 'size', 'keys') and response == 'ok':
            self._logger.debug('Receiving value')
            response = talk.get()
            if not response:
                self._logger.error('Failed to receive value')
                return None

        if request.action in ('keys',):
            response = pickle.loads(response)

        self._logger.debug('Closing connection')
        try:
            sock.shutdown(socket.SHUT_RDWR)
        except:
            self._logger.error('Failed to shutdown')
        sock.close()

        return response
124094
def accept(self):
        """"""
        newsock, addr = socket.accept(self)
        ssl_sock = SSLSocket(newsock._sock,
                             keyfile=self.keyfile,
                             certfile=self.certfile,
                             server_side=True,
                             cert_reqs=self.cert_reqs,
                             ssl_version=self.ssl_version,
                             ca_certs=self.ca_certs,
                             do_handshake_on_connect=self.do_handshake_on_connect,
                             suppress_ragged_eofs=self.suppress_ragged_eofs,
                             ciphers=self.ciphers)
        return ssl_sock, addr
1247377
def _send_to_address(self, address, data, timeout=10):
        
        # Socket to talk to server
        socket = get_context().socket(REQ)
        try:
            socket.setsockopt(LINGER, timeout * 1000)
            if address.find(":") == -1:
                socket.connect("tcp://%s:%d" % (address, self.default_port))
            else:
                socket.connect("tcp://%s" % address)
            socket.send_string(data)
            message = socket.recv_string()
            if message != "ok":
                LOGGER.warn("invalid acknowledge received: %s" % message)

        finally:
            socket.close()
7834
def accept(self):
        
        sock, address = self.sock.accept()
        wsock = websocket(sock)
        wsock.secure = self.secure
        ServerHandshake(wsock).perform(self)
        wsock.handshake_sent = True
        return wsock, address
665032
public void bind(InetSocketAddress address) throws IOException {
        if (listener != null) {
            listener.close();
            listener = null;
        }
        listener = ServerSocketChannel.open();
        listener.socket().bind(address);
    }