List of usage examples for java.net ServerSocket ServerSocket
public ServerSocket(int port) throws IOException
From source file:com.meschbach.psi.tomcat6.Tomcat6Builder.java
/** * The following method is ugly. Horribly ugly. But its a necessity * unfortunately due to Tomcat sprinkling copies of data everywhere. *//*from www . j a va 2 s . c o m*/ public int findOpenPort() throws PSIException { ServerSocket s = null; try { s = new ServerSocket(0); return s.getLocalPort(); } catch (IOException e) { throw new PSIException(e); } finally { if (s != null) { try { s.close(); } catch (IOException ioe) { throw new PSIException(ioe); } } } }
From source file:com.reversemind.hypergate.server.HyperGateServer.java
/** * Detect free setPort on System//from ww w . j a v a 2 s. c o m * * @return */ private int detectFreePort() { try { ServerSocket serverSocket = new ServerSocket(0); if (serverSocket.getLocalPort() == -1) { System.exit(-100); throw new RuntimeException( "\n\nCould not start HyperGateServer there are no any free port in the system available"); } int detectedPortNumber = serverSocket.getLocalPort(); serverSocket.close(); int count = 0; while (!serverSocket.isClosed()) { if (count++ > 10) { throw new RuntimeException("Could not start HyperGateServer"); } try { Thread.sleep(100); LOG.info("Waiting for closing auto discovered socket try number#" + count); } catch (InterruptedException e) { System.exit(-100); throw new RuntimeException("Could not start HyperGateServer"); } } serverSocket = null; return detectedPortNumber; } catch (IOException e) { e.printStackTrace(); } throw new RuntimeException("Could not start HyperGateServer 'cause no any available free port in system"); }
From source file:com.talis.jersey.apitest.DefaultExceptionMapperAcceptanceTest.java
private int findFreePort() throws IOException { ServerSocket serverSocket = new ServerSocket(0); int localPort = serverSocket.getLocalPort(); serverSocket.close();/* w ww.ja va2 s.co m*/ return localPort; }
From source file:org.red5.server.service.ShutdownServer.java
/** * Starts internal server listening for shutdown requests. *///from ww w. ja v a 2 s .com public void start() { // dump to stdout System.out.printf("Token: %s%n", token); // write out the token to a file so that red5 may be shutdown external to this VM instance. try { // delete existing file Files.deleteIfExists(Paths.get(shutdownTokenFileName)); // write to file Path path = Files.createFile(Paths.get(shutdownTokenFileName)); File tokenFile = path.toFile(); RandomAccessFile raf = new RandomAccessFile(tokenFile, "rws"); raf.write(token.getBytes()); raf.close(); } catch (Exception e) { log.warn("Exception handling token file", e); } while (!shutdown.get()) { try (ServerSocket serverSocket = new ServerSocket(port); Socket clientSocket = serverSocket.accept(); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));) { log.info("Connected - local: {} remote: {}", clientSocket.getLocalSocketAddress(), clientSocket.getRemoteSocketAddress()); String inputLine = in.readLine(); if (inputLine != null && token.equals(inputLine)) { log.info("Shutdown request validated using token"); out.println("Ok"); shutdownOrderly(); } else { out.println("Bye"); } } catch (BindException be) { log.error("Cannot bind to port: {}, ensure no other instances are bound or choose another port", port, be); shutdownOrderly(); } catch (IOException e) { log.warn("Exception caught when trying to listen on port {} or listening for a connection", port, e); } } }
From source file:node.Mailbox.java
/** * main loop/*from ww w . j a v a 2 s . co m*/ */ @Override public void run() { Socket socket = null; // set up server socket try { if (backlog == 0) { serverSocket = new ServerSocket(port); } else { serverSocket = new ServerSocket(port, backlog); } serverSocket.setSoTimeout(100); println("Opened up server socket on port " + port); } catch (SocketException e) { Control.logOneTime(e.getLocalizedMessage(), Level.SEVERE); println(e.getLocalizedMessage()); System.exit(-1); } catch (IOException e) { Control.logOneTime( "Mailbox error: could not listen on port " + port + ". stacktrace: " + e.getLocalizedMessage(), Level.SEVERE); e.printStackTrace(); log.severe(ExceptionUtils.getStackTrace(e)); System.exit(-1); } // enter main loop while (!shutdown) { if (REPORT) reportSend.add(report()); println(report().toJSONString()); // block until a connection is accepted println("Waiting for a connection"); try { socket = serverSocket.accept(); InetAddress inetaddr = socket.getInetAddress(); println("Received connection from " + inetaddr); // get the message id, then call the appropriate message handler acceptMessage(socket); // close the socket socket.close(); } catch (SocketTimeoutException e) { println("No connection: socket timed out", true); } catch (ConnectException e) { println("Caught ConnectException", true); } catch (SocketException e) { println("Caught SocketException", true); } catch (IOException e) { e.printStackTrace(); log.severe(ExceptionUtils.getStackTrace(e)); } // See if we have any messages to send if (msgsSend.size() > 0) println("Have " + msgsSend.size() + " messages to send"); while (msgsSend.size() > 0) { MessageWrapper<AbstractMessage> currentMsg = msgsSend.remove(); println("Current message: " + currentMsg.toString()); NodeListEntry nle_dest = currentMsg.nle; String destID = currentMsg.destID; printMessageSize(currentMsg); currentMsg.msg.scheduleSend(nodeList, destID, nle_dest); println("Mailbox: Message of type " + currentMsg.msg.msgType + " with id# " + currentMsg.msg.msgID + " scheduled for sending to " + nle_dest.toString()); } // check if it's time to shut down (signaled from Control) if (shutdown) { // write a log message, then exit // serverSocket.close() println("Mailbox exited"); return; } try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); log.severe(ExceptionUtils.getStackTrace(e)); } } }
From source file:org.apache.flink.streaming.api.functions.sink.SocketClientSinkTest.java
@Test public void testSocketSinkNoRetry() throws Exception { final ServerSocket server = new ServerSocket(0); final int port = server.getLocalPort(); try {/* w ww. j a v a 2s. c o m*/ final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); Thread serverRunner = new Thread("Test server runner") { @Override public void run() { try { Socket sk = server.accept(); sk.close(); } catch (Throwable t) { error.set(t); } } }; serverRunner.start(); SocketClientSink<String> simpleSink = new SocketClientSink<>(host, port, simpleSchema, 0, true); simpleSink.open(new Configuration()); // wait socket server to close serverRunner.join(); if (error.get() != null) { Throwable t = error.get(); t.printStackTrace(); fail("Error in server thread: " + t.getMessage()); } try { // socket should be closed, so this should trigger a re-try // need two messages here: send a fin to cancel the client state:FIN_WAIT_2 while the server is CLOSE_WAIT while (true) { // we have to do this more often as the server side closed is not guaranteed to be noticed immediately simpleSink.invoke(TEST_MESSAGE + '\n'); } } catch (IOException e) { // check whether throw a exception that reconnect failed. assertTrue("Wrong exception", e.getMessage().contains(EXCEPTION_MESSGAE)); } catch (Exception e) { fail("wrong exception: " + e.getClass().getName() + " - " + e.getMessage()); } assertEquals(0, simpleSink.getCurrentNumberOfRetries()); } finally { IOUtils.closeQuietly(server); } }
From source file:com.lithium.flow.vault.AgentVault.java
private int findFreePort() throws IOException { try (ServerSocket server = new ServerSocket(0)) { return server.getLocalPort(); }/*from w w w . j ava2 s. c o m*/ }
From source file:IntergrationTest.OCSPIntegrationTest.java
/** * Method to test a port is available.// w w w. j av a 2s . c o m * * @param port * * @return */ private boolean available(int port) { if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) { throw new IllegalArgumentException("Invalid start port: " + port); } ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); ds = new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch (IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { /* should not be thrown */ } } } return false; }
From source file:net.mybox.mybox.Server.java
/** * Constructor/*from w w w . ja va2 s. co m*/ * @param configFile */ public Server(String configFile) { printMessage("Starting server"); printMessage("config: " + configFile); LoadConfig(configFile); printMessage("database: " + accountsDbfile); accountsDb = new AccountsDB(accountsDbfile); try { printMessage("Binding to port " + port + ", please wait ..."); server = new ServerSocket(port); printMessage("Server started: " + server); while (true) { try { printMessage("Waiting for a client ..."); addClient(server.accept()); } catch (IOException ioe) { printMessage("Server accept error: " + ioe); } } } catch (IOException ioe) { printErrorExit("Can not bind to port " + port + ": " + ioe.getMessage()); } }