Listen for clients on a Unix socket.
        Returns the socket name.
357281
def listen_on_socket(self, socket_name=None):
        
        def connection_cb(pipe_connection):
            # We have to create a new `context`, because this will be the scope for
            # a new prompt_toolkit.Application to become active.
            with context():
                connection = ServerConnection(self, pipe_connection)

            self.connections.append(connection)

        self.socket_name = bind_and_listen_on_socket(socket_name, connection_cb)

        # Set session_name according to socket name.
#        if '.' in self.socket_name:
#            self.session_name = self.socket_name.rpartition('.')[-1]

        logger.info('Listening on %r.' % self.socket_name)
        return self.socket_name
469571
def return_socket(self, sock_info):
        """"""
        if self.pid != os.getpid():
            self.reset()
        else:
            if sock_info.pool_id != self.pool_id:
                sock_info.close()
            elif not sock_info.closed:
                sock_info.update_last_checkin_time()
                with self.lock:
                    self.sockets.appendleft(sock_info)

        self._socket_semaphore.release()
        with self.lock:
            self.active_sockets -= 1
78829
async def unixlisten(path, onlink):
    '''
    
    '''
    info = {'path': path, 'unix': True}
    async def onconn(reader, writer):
        link = await Link.anit(reader, writer, info=info)
        link.schedCoro(onlink(link))
    return await asyncio.start_unix_server(onconn, path=path)
1147380
public String getServerAddr()
    {
        if (_connection instanceof Socket)
            return ((Socket)_connection).getLocalAddress().getHostAddress();
        return _listener.getHost();
    }
741039
def run(self, address, port, unix_path):
        
        assert address or unix_path
        if unix_path:
            sock = bind_unix_socket(unix_path)
        else:
            sock = bind_socket(address, port)
        if sock is None:
            return False

        sock.setblocking(False)
        inputs = [sock]
        outputs = []
        try:
            while True:
                readable, _, _ = select.select(
                    inputs, outputs, inputs, SCHEDULER_CHECK_PERIOD)
                for r_socket in readable:
                    if unix_path and r_socket is sock:
                        client_stream, _ = sock.accept()
                        logger.debug("New connection from %s", unix_path)
                        self.handle_client_stream(client_stream, True)
                    else:
                        client_stream = self.new_client_stream(sock)
                        if client_stream is None:
                            continue
                        self.handle_client_stream(client_stream, False)
                    close_client_stream(client_stream, unix_path)
                self.scheduler()
        except KeyboardInterrupt:
            logger.info("Received Ctrl-C shutting-down ...")
        finally:
            sock.shutdown(socket.SHUT_RDWR)
            sock.close()
1351169
def serve(name: str = "", port: int = 5000) -> None:
    
    logging.info(" * Listening on port %s", port)
    httpd = HTTPServer((name, port), RequestHandler)
    httpd.serve_forever()
248068
def connect_unix
    D "opening connection to #{@socket_path}..."
    s = Timeout.timeout(@open_timeout) { UNIXSocket.open(@socket_path) }
    D "opened"
    @socket = BufferedIO.new(s)
    @socket.read_timeout = @read_timeout
    @socket.continue_timeout = @continue_timeout
    @socket.debug_output = @debug_output
    on_connect
  end
1334642
def receive_connection():
    
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("localhost", 8080))
    server.listen(1)
    client = server.accept()[0]
    server.close()
    return client
338592
def _write_named_sockets(self, socket_map):
    """"""
    for socket_name, socket_info in socket_map.items():
      self.write_named_socket(socket_name, socket_info)
1127679
def serve(self):
    """"""
    # We don't have to trap KeyboardInterrupt or SystemExit here,

    # Select the appropriate socket
    if isinstance(self.bind_addr, basestring):
      # AF_UNIX socket

      # So we can reuse the socket...
      try: os.unlink(self.bind_addr)
      except: pass

      # So everyone can access the socket...
      try: os.chmod(self.bind_addr, 0777)
      except: pass

      info = [(socket.AF_UNIX, socket.SOCK_STREAM, 0, "", self.bind_addr)]
    else:
      # AF_INET or AF_INET6 socket
      # Get the correct address family for our host (allows IPv6 addresses)
      host, port = self.bind_addr
      try:
        info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                      socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
      except socket.gaierror:
        # Probably a DNS issue. Assume IPv4.
        info = [(socket.AF_INET, socket.SOCK_STREAM, 0, "", self.bind_addr)]

    self.socket = None
    msg = "No socket could be created"
    for res in info:
      af, socktype, proto, canonname, sa = res
      #~ print res
      try:
        self.bind(af, socktype, proto)
      except socket.error, msg:
        if self.socket:
          self.socket.close()
        self.socket = None
        continue
      break
    if not self.socket:
      raise socket.error, msg

    self.socket.listen(self.request_queue_size)
    with closing(self.socket):
      while True:
        try:
          s, addr = yield sockets.Accept(self.socket, timeout=-1)
          s.settimeout(self.sockoper_timeout)
        except Exception, exc:
          # make acceptor more robust in the face of weird
          # accept bugs, XXX: but we might get a infinite loop

          #~ import warnings
          #~ warnings.warn("Accept thrown an exception: %s" % exc)

          import traceback
          traceback.print_exc()
          continue

        environ = self.environ.copy()
        environ["SERVER_SOFTWARE"] = self.version
        # set a non-standard environ entry so the WSGI app can know what
        # the *real* server protocol is (and what features to support).
        # See http://www.faqs.org/rfcs/rfc2145.html.
        environ["ACTUAL_SERVER_PROTOCOL"] = self.protocol
        environ["SERVER_NAME"] = self.server_name

        if isinstance(self.bind_addr, basestring):
          # AF_UNIX. This isn't really allowed by WSGI, which doesn't
          # address unix domain sockets. But it's better than nothing.
          environ["SERVER_PORT"] = ""
        else:
          environ["SERVER_PORT"] = str(self.bind_addr[1])
          # optional values
          # Until we do DNS lookups, omit REMOTE_HOST
          environ["REMOTE_ADDR"] = addr[0]
          environ["REMOTE_PORT"] = str(addr[1])

        conn = self.ConnectionClass(s, self.wsgi_app, environ,
          self.sendfile_timeout)
        yield events.AddCoro(conn.run, prio=priority.LAST if
                                     self.sockaccept_greedy else priority.FIRST)
68943
def _get_socketpair(self):
        
        try:
            return self._cls_idle_socketpairs.pop()  # pop() must be atomic
        except IndexError:
            rsock, wsock = socket.socketpair()
            set_cloexec(rsock.fileno())
            set_cloexec(wsock.fileno())
            self._cls_all_sockets.extend((rsock, wsock))
            return rsock, wsock
1073158
def listen_loop(self, address, family, internal=False):
        
        try:
            sock = eventlet.listen(address, family)
        except socket.error, e:
            if e.errno == errno.EADDRINUSE:
                logging.critical("Cannot listen on (%s, %s): already in use" % (address, family))
                raise
            elif e.errno == errno.EACCES and address[1] <= 1024:
                logging.critical("Cannot listen on (%s, %s) (you might need to launch as root)" % (address, family))
                return
            logging.critical("Cannot listen on (%s, %s): %s" % (address, family, e))
            return
        # Sleep to ensure we've dropped privileges by the time we start serving
        eventlet.sleep(0.5)
        # Start serving
        logging.info("Listening for requests on %s" % (address, ))
        try:
            eventlet.serve(
                sock,
                lambda sock, addr: self.handle(sock, addr, internal),
                concurrency = 10000,
            )
        finally:
            sock.close()
378248
def get_socket(self):
        """"""
        import eventlet

        # Separate out socket.listen arguments
        socket_args = {}
        for arg in ('backlog', 'family'):
            try:
                socket_args[arg] = self.options.pop(arg)
            except KeyError:
                pass
        # Separate out wrap_ssl arguments
        ssl_args = {}
        for arg in ('keyfile', 'certfile', 'server_side', 'cert_reqs',
                    'ssl_version', 'ca_certs', 'do_handshake_on_connect',
                    'suppress_ragged_eofs', 'ciphers'):
            try:
                ssl_args[arg] = self.options.pop(arg)
            except KeyError:
                pass
        address = (self.host, self.port)
        try:
            sock = eventlet.listen(address, **socket_args)
        except TypeError:
            # Fallback, if we have old version of eventlet
            sock = eventlet.listen(address)
        if ssl_args:
            sock = eventlet.wrap_ssl(sock, **ssl_args)
        return sock
370387
def select_sockets(self, timeout=None):
        
        if timeout is not None:
            t = time.time()
        while True:
            try:
                ready, __, __ = select.select(self.sockets(), (), (), timeout)
            except ValueError:
                # there's fd=0 socket.
                pass
            except select.error as exc:
                # ignore an interrupted system call.
                if exc.args[0] != EINTR:
                    raise
            else:
                # succeeded.
                return ready
            # retry.
            if timeout is None:
                continue
            # decrease timeout.
            t2 = time.time()
            timeout -= t2 - t
            t = t2
            if timeout <= 0:
                # timed out.
                return []
516342
def _bind_socket(self, bindaddr):
        """"""
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setblocking(0)
        try:
            sock.bind(bindaddr)
        except Exception:
            self._logger.exception("Unable to bind to %s" % str(bindaddr))
            raise
        sock.listen(self.BACKLOG)
        return sock
39220
def get_sockinfo (host, port=None):
    """"""
    family, socktype = socket.AF_INET, socket.SOCK_STREAM
    return socket.getaddrinfo(host, port, family, socktype)
661931
def interfaces(self):
        
        if 'interfaces' not in self._cached_values:
            self._cached_values['interfaces'] = []
            for name, interface in six.iteritems(self.settings.INTERFACES):
                listen = interface.get('LISTEN')
                unix_socket = interface.get('UNIX_SOCKET')
                if not listen and not unix_socket:
                    raise ValueError(
                        'Interface MUST listen either on TCP '
                        'or UNIX socket or both')
                host, port = parse_host(listen) if listen else (None, None)
                processes = int(interface.get('PROCESSES', 1))
                urls_obj_name = interface.get('URLS', '')
                if urls_obj_name:
                    urls = import_object(urls_obj_name)
                else:
                    urls = ()
                self._cached_values['interfaces'].append(
                    self.Interface(
                        name, host, port, unix_socket, processes, urls)
                )
        return self._cached_values['interfaces']