Starts the server, serves all enqueued requests, and shuts the server
down.

@param port the port to listen to, or 0 for any available port.
Automated tests should always use port 0 to avoid flakiness when a
specific port is unavailable.
166418
public void play(int port) throws IOException {
        if (acceptExecutor != null) {
            throw new IllegalStateException("play() already called");
        }
        // The acceptExecutor handles the Socket.accept() and hands each request off to the
        // requestExecutor. It also handles shutdown.
        acceptExecutor = Executors.newSingleThreadExecutor();
        // The requestExecutor has a fixed number of worker threads. In order to get strict
        // guarantees that requests are handled in the order in which they are accepted
        // workerThreads should be set to 1.
        requestExecutor = Executors.newFixedThreadPool(workerThreads);
        serverSocket = new ServerSocket(port);
        serverSocket.setReuseAddress(true);

        this.port = serverSocket.getLocalPort();
        acceptExecutor.execute(namedRunnable("MockWebServer-accept-" + port, new Runnable() {
            public void run() {
                try {
                    acceptConnections();
                } catch (Throwable e) {
                    logger.log(Level.WARNING, "MockWebServer connection failed", e);
                }

                /*
                 * This gnarly block of code will release all sockets and
                 * all thread, even if any close fails.
                 */
                try {
                    serverSocket.close();
                } catch (Throwable e) {
                    logger.log(Level.WARNING, "MockWebServer server socket close failed", e);
                }
                for (Iterator<Socket> s = openClientSockets.keySet().iterator(); s.hasNext(); ) {
                    try {
                        s.next().close();
                        s.remove();
                    } catch (Throwable e) {
                        logger.log(Level.WARNING, "MockWebServer socket close failed", e);
                    }
                }
                try {
                    acceptExecutor.shutdown();
                } catch (Throwable e) {
                    logger.log(Level.WARNING, "MockWebServer acceptExecutor shutdown failed", e);
                }
                try {
                    requestExecutor.shutdown();
                } catch (Throwable e) {
                    logger.log(Level.WARNING, "MockWebServer requestExecutor shutdown failed", e);
                }
            }

            private void acceptConnections() throws Exception {
                while (true) {
                    Socket socket;
                    try {
                        socket = serverSocket.accept();
                    } catch (SocketException e) {
                        return;
                    }
                    SocketPolicy socketPolicy = dispatcher.peek().getSocketPolicy();
                    if (socketPolicy == DISCONNECT_AT_START) {
                        dispatchBookkeepingRequest(0, socket);
                        socket.close();
                    } else {
                        openClientSockets.put(socket, true);
                        serveConnection(socket);
                    }
                }
            }
        }));
    }
837163
async def start(self):
        """"""

        await self.server.start()
        self.port = self.server.port
714488
function checkPort(port, cb) {
  var server = new net.Server();
  server.on('error', function (err) {
    server.removeAllListeners();
    cb(err);
  });
  server.listen(port, function () {
    server.on('close', function () {
      server.removeAllListeners();
      cb(null, port);
    });
    server.close();
  });
}
20899
@Override
	public synchronized void start() throws JMSException
    {
    	if (started)
    		return;
    	
    	log.info("Starting listener ["+getName()+"]");
    	
    	stopRequired = false;
    	
    	initServerSocket();
    	listenerThread = new Thread(this,"FFMQ-TCP-Server-"+serverSocket.getLocalPort());
    	listenerThread.start();
    	
    	started = true;
    }
134771
public void start() {
		if (socket == null) {
			throw new RuntimeException("Cannot bind a server that has not been initialized!");
		}
		running = true;

		Thread t = new Thread(this);
		t.setName("HttpServer");
		t.start();
	}
549407
@Override
    protected void shutDown() throws Exception {
        long traceId = LoggerHelpers.traceEnterWithContext(log, this.objectId, "shutDown");
        try {
            log.info("Stopping REST server listening on port: {}", this.restServerConfig.getPort());
            final GrizzlyFuture<HttpServer> shutdown = httpServer.shutdown(30, TimeUnit.SECONDS);
            log.info("Awaiting termination of REST server");
            shutdown.get();
            log.info("REST server terminated");
        } finally {
            LoggerHelpers.traceLeave(log, this.objectId, "shutDown", traceId);
        }
    }
257901
public void setPort( int port )
    {
        assert ( port >= 0 && port <= 65535 ) || ( port == UNDEFINED_PORT )
                 : "Invalid port" ;

        if ( ( port > 65535 ) || ( port < 0 && port != UNDEFINED_PORT ) )
        {
             throw new IllegalArgumentException( "A port must be between 0 and 65535 or equal to "
                                                 + UNDEFINED_PORT + ".");
        }

        _port = port;
    }
1285382
private ServerSocket createServerSocket(int port) throws IOException {
    try {
      ServerSocket sock = new ServerSocket();
      // Prevent 2MSL delay problem on server restarts
      sock.setReuseAddress(true);
      // Bind to listening port
      if (port == 0) {
        sock.bind(null);
        serverPort = sock.getLocalPort();
      } else {
        sock.bind(new InetSocketAddress(port));
      }
      return sock;
    } catch (IOException ioe) {
      throw new IOException("Could not create ServerSocket on port " + port + "." +
                            ioe);
    }
  }
1291206
def start!(port) # @todo Support other handlers http://www.rubydoc.info/github/rack/rack/Rack/Handler
      Rack::Handler.get(WEBRICK).run(self, Port: port) do |s|
        @server = s
        at_exit { stop! }
        [:INT, :TERM].each do |signal|
          old = trap(signal) do
            stop!
            old.call if old.respond_to?(:call)
          end
        end
      end
    end
892690
def start(self, port):
        
        self.application = tornado.web.Application(self.views, 
                template_path=self.templatePath, 
                static_path=self.staticPath)
        self.application.listen(port)
        self.ioloop.start()
441630
private void run(PortFile portFile, PrintStream err, int keepalive) {
        boolean fileDeleted = false;
        long timeSinceLastCompile;
        try {
            // Every 5 second (check_portfile_interval) we test if the portfile has disappeared => quit
            // Or if the last request was finished more than 125 seconds ago => quit
            // 125 = seconds_of_inactivity_before_shutdown+check_portfile_interval
            serverSocket.setSoTimeout(CHECK_PORTFILE_INTERVAL*1000);
            for (;;) {
                try {
                    Socket s = serverSocket.accept();
                    CompilerThread ct = compilerPool.grabCompilerThread();
                    ct.setSocket(s);
                    compilerPool.execute(ct);
                    flushLog();
                } catch (java.net.SocketTimeoutException e) {
                    if (compilerPool.numActiveRequests() > 0) {
                        // Never quit while there are active requests!
                        continue;
                    }
                    // If this is the timeout after the portfile
                    // has been deleted by us. Then we truly stop.
                    if (fileDeleted) {
                        log("Quitting because of "+(keepalive+CHECK_PORTFILE_INTERVAL)+" seconds of inactivity!");
                        break;
                    }
                    // Check if the portfile is still there.
                    if (!portFile.exists()) {
                        // Time to quit because the portfile was deleted by another
                        // process, probably by the makefile that is done building.
                        log("Quitting because portfile was deleted!");
                        flushLog();
                        break;
                    }
                    // Check if portfile.stop is still there.
                    if (portFile.markedForStop()) {
                        // Time to quit because another process touched the file
                        // server.port.stop to signal that the server should stop.
                        // This is necessary on some operating systems that lock
                        // the port file hard!
                        log("Quitting because a portfile.stop file was found!");
                        portFile.delete();
                        flushLog();
                        break;
                    }
                    // Does the portfile still point to me?
                    if (!portFile.stillMyValues()) {
                        // Time to quit because another build has started.
                        log("Quitting because portfile is now owned by another javac server!");
                        flushLog();
                        break;
                    }

                    // Check how long since the last request finished.
                    long diff = System.currentTimeMillis() - compilerPool.lastRequestFinished();
                    if (diff < keepalive * 1000) {
                        // Do not quit if we have waited less than 120 seconds.
                        continue;
                    }
                    // Ok, time to quit because of inactivity. Perhaps the build
                    // was killed and the portfile not cleaned up properly.
                    portFile.delete();
                    fileDeleted = true;
                    log("" + keepalive + " seconds of inactivity quitting in "
                        + CHECK_PORTFILE_INTERVAL + " seconds!");
                    flushLog();
                    // Now we have a second 5 second grace
                    // period where javac remote requests
                    // that have loaded the data from the
                    // recently deleted portfile can connect
                    // and complete their requests.
                }
            }
        } catch (Exception e) {
            e.printStackTrace(err);
            e.printStackTrace(theLog);
            flushLog();
        } finally {
            compilerPool.shutdown();
        }
        long realTime = System.currentTimeMillis() - serverStart;
        log("Shutting down.");
        log("Total wall clock time " + realTime + "ms build time " + totalBuildTime + "ms");
        flushLog();
    }
451073
public void startServer() {

    server = new Server(httpPort);
    server.setHandler(wrapHandlers());

    if (isWebSocketInClassPath()) {
      setupForWebSocket();
    }
    try {
      server.start();
      log().info("server started");

      Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownRunnable()));
      
      if (useStdInShutdown) {
        // generally for use in IDE via JettyRun, Use CTRL-D in IDE console to shutdown
        BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
        while((systemIn.readLine()) != null) {
          // ignore anything except CTRL-D by itself
        }
        System.out.println("Shutdown via CTRL-D");
        System.exit(0);
      }

    } catch (Exception e) {
      e.printStackTrace();
      System.exit(100);
    }
  }
43943
void configurePort(String port) {

        if (StringUtils.isNotBlank(port)) {
            try {
                this.port = Integer.parseInt(port);
                log.info("Using port {}", this.port);
            } catch (NumberFormatException e) {
                log.info("Unable to parse server PORT variable ({}). Defaulting to port {}", port, this.port);
            }
        }
    }
539989
@Override
	public void run() {
		stopped = false;
		try {
			try {
				serverSocket = new ServerSocket(port);
				serverSocket.setSoTimeout(TIMEOUT); // Block for maximum of 1.5 seconds
			} finally {
				// Notify when server socket has been created
				startupBarrier.countDown();
			}

			// Server: loop until stopped
			while (!isStopped()) {
				// get a semaphore so we can ensure below that no thread is still doing stuff when we want to close the server
				if (!semaphore.tryAcquire()) {
					throw new IllegalStateException("Could not get semaphore, number of possible threads is too low.");
				}

				try {
					// Start server socket and listen for client connections
					final Socket socket;
					try {
						socket = serverSocket.accept();
					} catch (@SuppressWarnings("unused") Exception e) {
						continue; // Non-blocking socket timeout occurred: try accept() again
					}

					// Get the input and output streams
					BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));         // NOSONAR - test class works only locally anyway
					PrintWriter out = new PrintWriter(socket.getOutputStream());       // NOSONAR - test class works only locally anyway

					synchronized (this) {
						/*
						 * We synchronize over the handle method and the list update because the client call completes inside
						 * the handle method and we have to prevent the client from reading the list until we've updated it.
						 * For higher concurrency, we could just change handle to return void and update the list inside the
						 * method
						 * to limit the duration that we hold the lock.
						 */
						List<SmtpMessage> messages = handleTransaction(out, input);
						receivedMail.addAll(messages);
					}
					socket.close();
				} finally {
					semaphore.release();
				}
			}
		} catch (Exception e) {
			// TODO: Should throw an appropriate exception here
			log.log(Level.SEVERE, "Caught exception: ", e);
		} finally {
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					log.log(Level.SEVERE, "Caught exception: ", e);
				}
			}
		}
	}
508991
@Override
    public void startServer(String name, int port, String messageOfTheDay)
    {
        for (final ClientListener listener : listeners)
        {
            network.addListener(listener);
        }
        network.addListener(this);
        network.setMessageOfTheDay(messageOfTheDay);
        network.start(name, port);
    }
239807
protected void closeServerSocket() {
    ServerSocket serverSocket = getServerSocket();

    if (!close(serverSocket)) {
      getLogger().warning(() -> String.format(
        "Failed to close ServerSocket bound to address [%s], listening on port [%d]",
          serverSocket.getInetAddress(), serverSocket.getLocalPort()));
    }
  }
1017511
@Handler
    public void onStart(Start event) throws IOException {
        closing = false;
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(serverAddress, backlog);
        MBeanView.addServer(this);
        fire(new NioRegistration(this, serverSocketChannel,
            SelectionKey.OP_ACCEPT, this), Channel.BROADCAST);
    }