Start the livereload server and accept incoming connections.
@return the port on which the server is listening
@throws IOException in case of I/O errors
490521
public int start() throws IOException {
		synchronized (this.monitor) {
			Assert.state(!isStarted(), "Server already started");
			logger.debug("Starting live reload server on port " + this.port);
			this.serverSocket = new ServerSocket(this.port);
			int localPort = this.serverSocket.getLocalPort();
			this.listenThread = this.threadFactory.newThread(this::acceptConnections);
			this.listenThread.setDaemon(true);
			this.listenThread.setName("Live Reload Server");
			this.listenThread.start();
			return localPort;
		}
	}
1040211
public void start() throws IOException {
    server.start();
    logger.info("Server started, listening on " + port);
    Runtime.getRuntime().addShutdownHook(new Thread() {
      @Override
      public void run() {
        // Use stderr here since the logger may has been reset by its JVM shutdown hook.
        System.err.println("*** shutting down gRPC server since JVM is shutting down");
        RouteGuideServer.this.stop();
        System.err.println("*** server shut down");
      }
    });
  }
207118
public void startUp() throws Exception {
    logger.info(String.format("Starting RPC server on port %d", port));
    ServerBootstrap bootstrap = new ServerBootstrap();

    ChannelFuture futureChannel = bootstrap.group(parentGroup, childGroup)
        .channel(channelClass)
        .childHandler(channelInitializer())
        .bind(port)
        .awaitUninterruptibly();

    if (futureChannel.isSuccess()) {
      this.channel = futureChannel.channel();
      logger.info("RPC server started successfully.");
    } else {
      logger.info("Failed to start RPC server.");
      throw new Exception(futureChannel.cause());
    }
  }
483633
protected synchronized ServerSocket initServerSocket() throws IOException, RetryableChannelException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "ServerSocket called, new ServerSocket needs to be created");
        }
        TCPChannelConfiguration channelConfig = tcpChannel.getConfig();

        IOException bindError = null;
        BindInfo earlyBind = portBoundEarly(channelConfig.getPort());

        if (earlyBind == null) {
            InetSocketAddress socketAddress = null;

            if (channelConfig.getHostname() == null) {
                socketAddress = new InetSocketAddress((InetAddress) null, channelConfig.getPort());
            } else {
                socketAddress = new InetSocketAddress(channelConfig.getHostname(), channelConfig.getPort());
            }

            if (!socketAddress.isUnresolved()) {
                serverSocket = openServerSocket();

                // receieve buffer size for accepted sockets is set on serverSocket,
                // send buffer size is set on individual sockets

                if ((channelConfig.getReceiveBufferSize() >= TCPConfigConstants.RECEIVE_BUFFER_SIZE_MIN)
                    && (channelConfig.getReceiveBufferSize() <= TCPConfigConstants.RECEIVE_BUFFER_SIZE_MAX)) {
                    serverSocket.setReceiveBufferSize(channelConfig.getReceiveBufferSize());
                }
                if (!channelConfig.getSoReuseAddress()) {
                    //Forced re-use==false custom property
                    try {
                        attemptSocketBind(socketAddress, false);
                    } catch (IOException e) {
                        // no FFDC
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Forced re-use==false bind attempt failed, ioe=" + e);
                        }
                        bindError = e;
                    }
                } else {
                    //re-use==true (default)
                    // try the standard startup attempts
                    try {
                        attemptSocketBind(socketAddress, false);
                        //If we are not on Windows and the bind succeeded, we should set reuseAddr=true
                        //for future binds.
                        if (!TCPFactoryConfiguration.isWindows()) {
                            this.serverSocket.setReuseAddress(true);
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(tc, "ServerSocket reuse set to true to allow for later override");
                            }
                        }
                    } catch (IOException ioe) {
                        // See if we got the error because the port is in waiting to be cleaned up.
                        // If so, no one should be accepting connections on it, and open should fail.
                        // If that's the case, we can set ReuseAddr to expedite the bind process.
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "ServerSocket bind failed on first attempt with IOException: " + ioe.getMessage());
                        }
                        bindError = ioe;
                        try {
                            String hostName = channelConfig.getHostname();
                            if (hostName == null) {
                                hostName = "localhost";
                            }
                            InetSocketAddress testAddr = new InetSocketAddress(hostName, channelConfig.getPort());
                            // PK40741 - test for localhost being resolvable before using it
                            if (!testAddr.isUnresolved()) {
                                SocketChannel testChannel = SocketChannel.open(testAddr);
                                // if we get here, socket opened successfully, which means
                                // someone is really listening
                                // so close connection and don't bother trying to bind again
                                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                    Tr.debug(tc, "attempt to connect to port to check listen status worked, someone else is using the port!");
                                }
                                testChannel.close();
                            } else {
                                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                    Tr.debug(tc, "Test connection addr is unresolvable; " + testAddr);
                                }
                            }
                        } catch (IOException testioe) {
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(tc, "attempt to connect to port to check listen status failed with IOException: " + testioe.getMessage());
                            }
                            try {
                                // open (or close) got IOException, retry with reuseAddr on
                                attemptSocketBind(socketAddress, true);
                                bindError = null;

                            } catch (IOException newioe) {
                                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                    Tr.debug(tc, "ServerSocket bind failed on second attempt with IOException: " + newioe.getMessage());
                                }
                                bindError = newioe;
                            }
                        }
                    }
                }

                if (bindError == null) {
                    // listen port can be different than config port if configed port is '0'
                    listenPort = serverSocket.getLocalPort();
                } else {
                    String displayableHostName = channelConfig.getDisplayableHostname();

                    // add in the exception message to help in problem diagnostics without tracing
                    Tr.error(tc, TCPChannelMessageConstants.BIND_ERROR,
                             new Object[] { channelConfig.getChannelData().getExternalName(), displayableHostName, String.valueOf(channelConfig.getPort()),
                                            bindError.getMessage() });

                    throw new RetryableChannelException(bindError.getMessage());
                }

            } else { // unresolved socket address
                String displayableHostName = channelConfig.getDisplayableHostname();
                Tr.error(tc, TCPChannelMessageConstants.LOCAL_HOST_UNRESOLVED,
                         new Object[] { channelConfig.getChannelData().getExternalName(), displayableHostName, String.valueOf(channelConfig.getPort()) });

                throw new RetryableChannelException(new IOException("local address unresolved"));
            }

        } else {
            // this port was bound earlier by a different service
            Exception e = earlyBind.getBindException();
            if (e == null) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Found early bind, setting serverSocket and listenPort");
                }

                serverSocket = earlyBind.getServerSocket();
                // listen port can be different than config port if configed port is '0'
                listenPort = serverSocket.getLocalPort();
            } else {

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Early Bind generated the following exception: " + e);
                }

                // add in the exception message to help in problem diagnostics without tracing
                Tr.error(tc, TCPChannelMessageConstants.BIND_ERROR,
                         new Object[] { channelConfig.getChannelData().getExternalName(), earlyBind.getHostname(), String.valueOf(earlyBind.getPort()), e.getMessage() });

                if (e instanceof IOException) {
                    throw (IOException) e;
                }
                if (e instanceof RetryableChannelException) {
                    throw (RetryableChannelException) e;
                }
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "new ServerSocket successfully created");
        }

        return this.serverSocket;
    }
968845
public static int getFreePort(int defaultPort) throws IOException {
    try (
        ServerSocket serverSocket = new ServerSocket(defaultPort)
    ) {
      return serverSocket.getLocalPort();
    } catch (IOException e) {
      return getFreePort();
    }
  }
566797
protected boolean initiateClient()
    {
        for (String host : hosts)
        {
            if (host == null || !StringUtils.isNumeric(port) || port.isEmpty())
            {
                logger.error("Host or port should not be null / port should be numeric");
                throw new IllegalArgumentException("Host or port should not be null / port should be numeric");
            }

            List<MongoCredential> credentials = MongoDBUtils.fetchCredentials(puMetadata.getProperties(),
                    externalProperties);
            ServerAddress addr;
            try
            {
                addr = new ServerAddress(host, Integer.parseInt(port));
            }
            catch (NumberFormatException ex)
            {
                throw new SchemaGenerationException(ex);
            }

            mongo = new MongoClient(addr, credentials);
            db = mongo.getDB(databaseName);
            return true;
        }
        return false;
    }
254651
public Server run() throws Exception {
        if (server == null) {
            server = new Server(port);
            String basePath = "/druid";
            buildSwagger(basePath);
            HandlerList handlers = new HandlerList();
            handlers.addHandler(buildContext(basePath));
            server.setHandler(handlers);
            server.start();
        } else {
            throw new IllegalStateException("Server already running");
        }
        return server;
    }
1221285
private void initSocket()
    throws IOException
  {
    _idleTimeout = _port.getKeepaliveTimeout();

    _port.ssl(_socket);

    writeStream().init(_socket.stream());

    // ReadStream cannot use getWriteStream or auto-flush
    // because of duplex mode
    // ReadStream is = getReadStream();
    _readStream.init(_socket.stream());

    if (log.isLoggable(Level.FINEST)) {
      log.finest(dbgId() + "starting connection " + this
                 + ", total=" + _port.getConnectionCount());
    }
  }
490923
def start_server(port):
    '''  '''
    s = socket(AF_INET, SOCK_STREAM)
    s.settimeout(None)

    try:
        from socket import SO_REUSEPORT
        s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
    except ImportError:
        s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

    s.bind(('', port))
    pydev_log.info("Bound to port :%s", port)

    try:
        s.listen(1)
        newSock, _addr = s.accept()
        pydev_log.info("Connection accepted")
        # closing server socket is not necessary but we don't need it
        s.shutdown(SHUT_RDWR)
        s.close()
        return newSock

    except:
        pydev_log.exception("Could not bind to port: %s\n", port)
283110
public void start() {
        logger.info("\n###starting...");
        try {
            Container container = this.getActualContainer();
            Server server = new ContainerServer(container);
            connection = new SocketConnection(server);
            SocketAddress address = new InetSocketAddress(port);
            socketAddress =(InetSocketAddress) connection.connect(address);
            this.isRunning = true;
            logger.info("\n#Simulator: " + this.getSimulatorName() +
                        "\n#started. " +
                        "\nListening at port: " + socketAddress.getPort());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
173265
protected SchedulerServer getServer(
      Config runtime, IScheduler scheduler, int port) throws IOException {

    // create an instance of the server using scheduler class and port
    return new SchedulerServer(runtime, scheduler, port);
  }
1003020
public void start() throws IOException {
    Preconditions.checkState(!isStarted(), "JN already running");
   
    journalNodes = getJournalHttpAddresses(conf);
    // crash the JournalNode if the DFS_JOURNALNODE_HOSTS is not configured.
    if (journalNodes.isEmpty()) {
      String msg = JournalConfigKeys.DFS_JOURNALNODE_HOSTS
          + " is not present in the configuration.";
      LOG.fatal(msg);
      throw new IOException(msg);
    }
    LOG.info("JournalNode hosts: " + journalNodes);
    
    validateAndCreateJournalDir(localDir);
    LOG.info("JournalNode storage: " + localDir.getAbsolutePath());
    
    InetSocketAddress socAddr = JournalNodeRpcServer.getAddress(conf);
    // TODO serverId has to be set correctly
    metrics = new JournalNodeMetrics(conf, socAddr.toString());
    
    httpServer = new JournalNodeHttpServer(conf, this);
    httpServer.start();

    rpcServer = new JournalNodeRpcServer(conf, this);
    rpcServer.start();
    
    journalSyncer = new JournalNodeJournalSyncer(journalNodes,
        httpServer.getAddress(), conf);
    journalSyncerThread = new Thread(journalSyncer, "Thread-JournalSyncer");
    journalSyncerThread.start();
  }
894838
private synchronized void connect() throws IOReactorException
    {
        if (m_connManager == null) {
            ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
            m_connManager = new PoolingNHttpClientConnectionManager(ioReactor);
            m_connManager.setMaxTotal(HTTP_EXPORT_MAX_CONNS);
            m_connManager.setDefaultMaxPerRoute(HTTP_EXPORT_MAX_CONNS);
        }

        if (m_client == null || !m_client.isRunning()) {
            HttpAsyncClientBuilder client = HttpAsyncClients.custom().setConnectionManager(m_connManager).
                    setRedirectStrategy(new HDFSUtils.HadoopRedirectStrategy());
            if (m_isKrb) {
                m_client = (CloseableHttpAsyncClient)Subject.doAs(m_context.getSubject(), new PrivilegedBuild(client));
            } else {
                m_client = client.build();
            }
            m_client.start();
        }
    }
1015106
public static int findFreePort() throws IOException {
        ServerSocket socket = null;

        try {
            socket = new ServerSocket(0);

            return socket.getLocalPort();
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }
332200
private ClientSocket connect()
  {
    if (_maxConnections <= _activeCount.get() + _startingCount.get()) {
      if (log.isLoggable(Level.WARNING)) {
        log.warning(this + " connect exceeded max-connections"
                    + "\n  max-connections=" + _maxConnections
                    + "\n  activeCount=" + _activeCount.get()
                    + "\n  startingCount=" + _startingCount.get());
      }
      
      return null;
    }

    _startingCount.incrementAndGet();

    State state = _state;
    
    if (! state.isInit()) {
      _startingCount.decrementAndGet();
      
      IllegalStateException e = new IllegalStateException(L.l("'{0}' connection cannot be opened because the server pool has not been started.", this));

      log.log(Level.WARNING, e.toString(), e);

      throw e;
    }
    
    if (getPort() <= 0) {
      return null;
    }
    
    long connectionStartTime = CurrentTime.currentTime();

    try {
      ReadWritePair pair = openTCPPair();
      ReadStreamOld rs = pair.getReadStream();
      rs.setEnableReadTime(true);
      
      //rs.setAttribute("timeout", new Integer((int) _loadBalanceSocketTimeout));

      _activeCount.incrementAndGet();
      
      _connectCountTotal.incrementAndGet();

      ClientSocket stream = new ClientSocket(this, _streamCount++,
                                               rs, pair.getWriteStream());

      if (log.isLoggable(Level.FINER))
        log.finer("connect " + stream);

      if (_firstSuccessTime <= 0) {
        if (_state.isStarting()) {
          if (_loadBalanceWarmupTime > 0)
            _state = State.WARMUP;
          else
            _state = State.ACTIVE;

          _firstSuccessTime = CurrentTime.currentTime();
        }

        if (_warmupState < 0)
          _warmupState = 0;
      }

      return stream;
    } catch (IOException e) {
      if (log.isLoggable(Level.FINEST))
        log.log(Level.FINEST, this + " " + e.toString(), e);
      else
        log.finer(this + " " + e.toString());

      failConnect(connectionStartTime);

      return null;
    } finally {
      _startingCount.decrementAndGet();
    }
  }
507798
public synchronized void start() throws IOException {
        if (listenerThreads.size() == 0) {
            List<InetAddress> addresses = hostAddress == null ? NetworkUtil.getMulticastAddresses() : Arrays.asList(hostAddress);
            if (addresses.size() == 0) {
                logHandler.info("No suitable address found for listening on multicast discovery requests");
                return;
            }
            // We start a thread for every address found
            for (InetAddress addr : addresses) {
                try {
                    MulticastSocketListenerThread thread = new MulticastSocketListenerThread("JolokiaDiscoveryListenerThread-" + addr.getHostAddress(),
                                                                                            addr,
                                                                                             detailsHolder,
                                                                                             restrictor,
                                                                                             logHandler);
                    thread.start();
                    listenerThreads.add(thread);
                } catch (IOException exp) {
                    logHandler.info("Couldn't start discovery thread for " + addr + ": " + exp);
                }
            }
        }
    }
689887
def start(self, tcpport=102):
        
        if tcpport != 102:
            logger.info("setting server TCP port to %s" % tcpport)
            self.set_param(snap7.snap7types.LocalPort, tcpport)
        logger.info("starting server on 0.0.0.0:%s" % tcpport)
        return self.library.Srv_Start(self.pointer)