Create a listening server socket.
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
344373
def bind_and_listen_on_win32_socket(socket_name, accept_callback):
    
    assert callable(accept_callback)
    socket_name = r'\\.\pipe\pymux.sock.jonathan.42'

    pipes = [PipeInstance(socket_name, pipe_connection_cb=accept_callback)
             for i in range(INSTANCES)]

    for p in pipes:
        # Start pipe.
        ensure_future(p.handle_pipe())

    return socket_name
227120
def create_server(
            self,
            loop: asyncio.AbstractEventLoop,
            sock: Any,
            ssl: SSLContext,
    ) -> TypeGenerator[Any, None, Server]:
        
        if loop is not None and self._loop is not loop:
            self._loop = loop
        return (yield from self.listen(
            sock=sock,
            ssl=ssl,
        ))
271824
public function listen()
    {
        $this->listener_ = @stream_socket_server(
            $this->host_ . ':' . $this->port_,
            $errno,
            $errstr,
            STREAM_SERVER_BIND | STREAM_SERVER_LISTEN,
            $this->context_
        );
    }
1096702
def create_local_socket (self):
        """"""
        sock = create_socket(socket.AF_UNIX, socket.SOCK_STREAM)
        addr = self['LocalSocket']
        try:
            sock.connect(addr)
        except socket.error:
            sock.close()
            raise
        return sock
140816
function onListening() {
    const addr = server.address();
    const bind = (typeof addr === 'string')
                ? 'pipe ' + addr
                : 'port ' + addr.port;
    debugServer('Listening on ' + bind);
  }
909468
def run(self):
    """"""
    self._live = True
    self._sock.settimeout(self.LISTEN_TIMEOUT_S)

    # Passing in INADDR_ANY means the kernel will choose the default interface.
    # The localhost address is used to receive messages sent in "local_only"
    # mode and the default address is used to receive all other messages.
    for interface_ip in (socket.INADDR_ANY, LOCALHOST_ADDRESS):
      self._sock.setsockopt(
          socket.IPPROTO_IP,
          socket.IP_ADD_MEMBERSHIP,
          # IP_ADD_MEMBERSHIP takes the 8-byte group address followed by the IP
          # assigned to the interface on which to listen.
          struct.pack('!4sL', socket.inet_aton(self.address), interface_ip))

    if sys.platform == 'darwin':
      self._sock.setsockopt(socket.SOL_SOCKET,
                            socket.SO_REUSEPORT,
                            1)  # Allow multiple listeners to bind.
    else:
      self._sock.setsockopt(socket.SOL_SOCKET,
                            socket.SO_REUSEADDR,
                            1)  # Allow multiple listeners to bind.
    self._sock.bind((self.address, self.port))

    while self._live:
      try:
        data, address = self._sock.recvfrom(MAX_MESSAGE_BYTES)
        data = data.decode('utf-8')
        log_line = 'Received multicast message from %s: %s' % (address, data)
        response = self._callback(data)
        if response is not None:
          log_line += ', responding with %s bytes' % len(response)
          # Send replies out-of-band instead of with the same multicast socket
          # so that multiple processes on the same host can listen for
          # requests and reply (if they all try to use the multicast socket
          # to reply, they conflict and this sendto fails).
          response = response.encode('utf-8')
          socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(
              response, address)
        _LOG.debug(log_line)
      except socket.timeout:
        pass
      except socket.error:
        _LOG.debug('Error receiving multicast message', exc_info=True)
971971
def listen(self):
        """"""

        msgtmpl = (u'Serving on host %(host)s:%(port)s')
        host = CONF.wsgi.wsgi_host
        port = CONF.wsgi.wsgi_port
        LOG.info(msgtmpl,
                 {'host': host, 'port': port})
        server_cls = self._get_server_cls(host)
        httpd = simple_server.make_server(host,
                                          port,
                                          self.app,
                                          server_cls)
        httpd.serve_forever()
1060401
function listen() {
  var args = []
    , port = this.conf.get(ConfigKey.PORT)
    , socket = this.conf.get(ConfigKey.UNIXSOCKET)
    , perm = this.conf.get(ConfigKey.UNIXSOCKETPERM)
    , backlog = this.conf.get(ConfigKey.TCP_BACKLOG)
    , cb = typeof arguments[arguments.length - 1] === 'function'
      ? arguments[arguments.length - 1] : null
    , tcp
    , unix;

  if(socket) {
    unix = this._unix = new UnixServer(this);
  }

  // tcp: server.listen(port, [host], [backlog], [callback])
  // unix socket: server.listen(path, [callback])

  // port zero means don't listen on a tcp port
  if(port !== 0) {
    tcp = this._tcp = new TcpServer(this);

    // port comes first
    args.unshift(port);

    // backlog is penultimate argument
    if(typeof backlog === 'number') {
      args.push(backlog);
    }

    //console.dir(args);

    // cb is last argument
    if(cb) args.push(cb);

    function onListen() {
      // for server info, the actual port or socket in use
      // stored on the state, null if listen was never called
      // or if the bind failed, could also be a unix socket
      var addr = tcp.address();
      var port = addr.port;
      this.state.addr = addr;

      // only write pid if we listen
      if(this._daemonized) {
        daemon.pid.write(this.conf);
      }

      this.emit('listen', port);
      this.log.notice('accepting connections on port %s', port);

      // might be listening on a unix socket too
      if(unix) unix.listen(socket, perm);
    }

    tcp.once('listening', onListen.bind(this));
    tcp.listen.apply(tcp, args);
  // just a unix socket
  }else if(unix) {
    unix.listen(socket, perm);
  }
}
479564
function listen(file, perm) {
  var args = [file]
    , perm = perm || 0700
    , server = this;

  this.file = file;
  this.name = path.basename(file);

  if(this.name === file) {
    file = path.join(process.cwd(), file);
  }

  function onListen() {
    try {
      fs.chmodSync(file, perm);
    }catch(e){}
    log.notice('accepting connections at %s', file);
  }
  args.push(onListen);

  // jump through some hoops for stale sockets
  server.on('error', function (e) {
    if(e.code == 'EADDRINUSE') {
      var client = new net.Socket();
      // handle error trying to talk to server
      client.on('error', function(e) {
        // no other server listening
        if(e.code == 'ECONNREFUSED') {
          fs.unlinkSync(file);
          TcpServer.prototype.listen.apply(server, args);
        }
      });
      client.connect({path: file}, function() {
        // exit with original EADDRINUSE
        throw e;
      });
    }
  });
  Server.prototype.listen.apply(server, args);
}
1108036
def _create_socket(self):
        
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s = ssl.wrap_socket(s)
        s.connect((self.host, self.__port))
        s.settimeout(self.timeout)
        return s
396897
async def create_server(self, worker, protocol_factory, address=None,
                            sockets=None, idx=0):
        '''
        '''
        cfg = self.cfg
        max_requests = cfg.max_requests
        if max_requests:
            max_requests = int(lognormvariate(log(max_requests), 0.2))
        server = self.server_factory(
            protocol_factory,
            loop=worker._loop,
            max_requests=max_requests,
            keep_alive=cfg.keep_alive,
            name=self.name,
            logger=self.logger,
            server_software=cfg.server_software,
            cfg=cfg,
            idx=idx
        )
        for event in ('connection_made', 'pre_request', 'post_request',
                      'connection_lost'):
            callback = getattr(cfg, event)
            if callback != pass_through:
                server.event(event).bind(callback)
        await server.start_serving(
            sockets=sockets,
            address=address,
            backlog=cfg.backlog,
            sslcontext=self.sslcontext()
        )
        return server
1334748
function listen(port, cb) {
    return new Promise((resolve, reject) => {
        let completed = ssocket_helpers.createSimplePromiseCompletedAction(resolve, reject);
        try {
            let serverToClient;
            let server = Net.createServer((connectionWithClient) => {
                try {
                    if (cb) {
                        cb(null, createServer(connectionWithClient));
                    }
                }
                catch (e) {
                    if (cb) {
                        cb(e);
                    }
                }
            });
            let isListening = false;
            server.once('error', (err) => {
                if (!isListening && err) {
                    completed(err);
                }
            });
            server.on('listening', () => {
                isListening = true;
                completed(null, server);
            });
            server.listen(port);
        }
        catch (e) {
            completed(e);
        }
    });
}
1145272
def server_socket(self, config):
		
		if self.__server_socket is None:
			self.__server_socket = self.create_server_socket(config)
			self.__server_socket.bind(self.bind_socket(config).pair())
		return self.__server_socket
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)
921245
def server_thread(sock, handle_conn, quit_event):
    """"""
    log.debug('server thread started')

    def accept_connection():
        conn, _ = sock.accept()
        conn.settimeout(None)
        return conn

    while True:
        log.debug('waiting for connection on %s', sock.getsockname())
        try:
            conn = retry(accept_connection, socket.timeout, quit_event)
        except StopIteration:
            log.debug('server stopped')
            break
        # Handle connections from SSH concurrently.
        threading.Thread(target=handle_conn,
                         kwargs=dict(conn=conn)).start()
    log.debug('server thread stopped')
202908
function setupListener (host_port, listenerDone) {

            const hp = /^\[?([^\]]+)\]?:(\d+)$/.exec(host_port);
            if (!hp) return listenerDone(
                new Error('Invalid "listen" format in smtp.ini'));

            const host = hp[1];
            const port = parseInt(hp[2], 10);

            Server.get_smtp_server(host, port, inactivity_timeout, (server) => {
                if (!server) return listenerDone();

                server.notes = Server.notes;
                if (Server.cluster) server.cluster = Server.cluster;

                server
                    .on('listening', function () {
                        const addr = this.address();
                        logger.lognotice(`Listening on ${addr.address}:${addr.port}`);
                        listenerDone();
                    })
                    .on('close', () => {
                        logger.loginfo(`Listener ${host}:${port} stopped`);
                    })
                    .on('error', e => {
                        if (e.code !== 'EAFNOSUPPORT') return listenerDone(e);
                        // Fallback from IPv6 to IPv4 if not supported
                        // But only if we supplied the default of [::0]:25
                        if (/^::0/.test(host) && Server.default_host) {
                            server.listen(port, '0.0.0.0', 0);
                            return;
                        }
                        // Pass error to callback
                        listenerDone(e);
                    })
                    .listen(port, host, 0);
            });
        }