List of usage examples for java.net ServerSocket close
public void close() throws IOException
From source file:com.chinamobile.bcbsp.workermanager.WorkerManager.java
@Override public synchronized int getFreePort() { ServerSocket s; this.currentFreePort = this.currentFreePort + 1; int count = 0; for (; this.currentFreePort <= 65536; this.currentFreePort++) { count++;/*from w w w. j a va2 s . c o m*/ if (count > 5535) { LOG.info("[WorkerManager: getFreePort()] attempts " + "to get a free port over 5535 times!"); return 60000; } if (this.currentFreePort > 65535) { this.currentFreePort = 60001; } try { LOG.info("debug:this.currentFreePort is " + this.currentFreePort); s = new ServerSocket(this.currentFreePort); s.close(); return this.currentFreePort; } catch (IOException e) { LOG.info("debug:this.currentFreePort is " + this.currentFreePort); LOG.error("[WokerManager] caught", e); } } return 60000; }
From source file:org.bml.util.server.BServer.java
/** * The runInvProxy class starts a new server socket and listens for * connections from clients. Upon recieving a connection, it starts a new * InvProxyThread to process the connection. * @param aPort The port to attach to/*from ww w .j a v a 2 s . co m*/ * @param aNumThreads the number of worker threads * @param aSleepTime sleep time in between checks * @param aMaxQueueLength the max requests to queue up * @param accessLog a Log to write access info */ public void runInvProxy(int aPort, int aNumThreads, long aSleepTime, int aMaxQueueLength, Log accessLog) { this.accessLog = accessLog; if (LOG.isDebugEnabled()) { LOG.debug("Attempting to start server on port: " + aPort); } //Start Server ServerSocket myServerSocket = null; try { myServerSocket = new ServerSocket(aPort, aMaxQueueLength); } catch (IOException e) { System.out.println(e); return; } if (LOG.isDebugEnabled()) { LOG.debug("Server started on port: " + aPort); } //Continuously accept connections and start threads to //process connections. while (!theDone) { if (LOG.isDebugEnabled()) { LOG.debug("Ready to accept client connection"); } Socket myClientSocket = null; try { myClientSocket = myServerSocket.accept(); } catch (IOException e) { System.out.println("Accept Error: " + e); break; } if (LOG.isDebugEnabled()) { LOG.debug("Accepted connection from client: " + myClientSocket.getInetAddress() + "\nStarting thread to deal with connection"); } //Make sure there aren't too many active threads if (aNumThreads != -1) { while (Thread.activeCount() > aNumThreads) { if (LOG.isDebugEnabled()) { LOG.debug("Too many active threads. Waiting " + aSleepTime + "(ms) before trying to start new HitServerInvProxyThread again"); } try { Thread.sleep(aSleepTime); } catch (InterruptedException e) { System.out.println(e); break; } } } if (myClientSocket != null && myClientSocket.isConnected()) { new InvProxyThread(this, myClientSocket, this.accessLog); } else { if (LOG.isWarnEnabled()) { LOG.warn("Client Socket is null or not connected when starting thread"); } break; } } //Closing socket if (LOG.isDebugEnabled()) { LOG.debug("Closing server socket. In general, we should never get here."); } try { myServerSocket.close(); } catch (IOException e) { System.out.println(e); return; } }
From source file:tv.phantombot.PhantomBot.java
public void checkPortAvailabity(int port) { ServerSocket serverSocket = null; try {/*from w w w . j a va 2 s . com*/ serverSocket = bindIP.isEmpty() ? new ServerSocket(port) : new ServerSocket(port, 1, java.net.InetAddress.getByName(bindIP)); serverSocket.setReuseAddress(true); } catch (IOException e) { com.gmt2001.Console.err.println("Port is already in use: " + port); com.gmt2001.Console.err.println("Ensure that another copy of PhantomBot is not running."); com.gmt2001.Console.err .println("If another copy is not running, try to change baseport in ./config/botlogin.txt"); com.gmt2001.Console.err.println("PhantomBot will now exit."); System.exit(0); } finally { if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { com.gmt2001.Console.err.println("Unable to close port for testing: " + port); com.gmt2001.Console.err.println("PhantomBot will now exit."); System.exit(0); } } } }
From source file:org.eredlab.g4.ccl.net.ftp.FTPClient.java
/** * Establishes a data connection with the FTP server, returning * a Socket for the connection if successful. If a restart * offset has been set with {@link #setRestartOffset(long)}, * a REST command is issued to the server with the offset as * an argument before establishing the data connection. Active * mode connections also cause a local PORT command to be issued. * <p>/*from w w w.j a v a2 s . com*/ * @param command The text representation of the FTP command to send. * @param arg The arguments to the FTP command. If this parameter is * set to null, then the command is sent with no argument. * @return A Socket corresponding to the established data connection. * Null is returned if an FTP protocol error is reported at * any point during the establishment and initialization of * the connection. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. */ protected Socket _openDataConnection_(int command, String arg) throws IOException { Socket socket; if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE && __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE) return null; if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE) { ServerSocket server; server = _socketFactory_.createServerSocket(0, 1, getLocalAddress()); if (!FTPReply.isPositiveCompletion(port(getLocalAddress(), server.getLocalPort()))) { server.close(); return null; } if ((__restartOffset > 0) && !restart(__restartOffset)) { server.close(); return null; } if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { server.close(); return null; } // For now, let's just use the data timeout value for waiting for // the data connection. It may be desirable to let this be a // separately configurable value. In any case, we really want // to allow preventing the accept from blocking indefinitely. if (__dataTimeout >= 0) server.setSoTimeout(__dataTimeout); socket = server.accept(); server.close(); } else { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) return null; __parsePassiveModeReply((String) _replyLines.elementAt(0)); socket = _socketFactory_.createSocket(__passiveHost, __passivePort); if ((__restartOffset > 0) && !restart(__restartOffset)) { socket.close(); return null; } if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { socket.close(); return null; } } if (__remoteVerificationEnabled && !verifyRemote(socket)) { InetAddress host1, host2; host1 = socket.getInetAddress(); host2 = getRemoteAddress(); socket.close(); throw new IOException("Host attempting data connection " + host1.getHostAddress() + " is not same as server " + host2.getHostAddress()); } if (__dataTimeout >= 0) socket.setSoTimeout(__dataTimeout); return socket; }
From source file:uk.ac.soton.itinnovation.sad.service.services.EccIntegrationService.java
public boolean start() { logger.debug("Initialising ECC Integration service"); createdProcesses = new ArrayList<>(); boolean result = true; // If ECC intagration enabled if (!configurationService.getConfiguration().isEccEnabled()) { logger.debug("Nothing to do, ECC integration disabled"); } else {//w w w. ja v a2 s .com // Discover plugins JSONObject pluginInfo; String pathToPlugins = pluginsService.getAbsolutePluginsPath(); JSONObject currentSadConfig = JSONObject.fromObject(configurationService.getConfiguration()); String configurationFilePath; try { File tmp = File.createTempFile("sadconfiguration", ".json"); tmp.deleteOnExit(); File coordinatorPath = new File(configurationService.getConfiguration().getCoordinatorPath()); currentSadConfig.put("coordinatorPathAbs", coordinatorPath.getAbsolutePath()); FileWriter fileWriter = new FileWriter(tmp); fileWriter.write(currentSadConfig.toString()); fileWriter.close(); configurationFilePath = tmp.getAbsolutePath(); logger.debug("Stored current configuration for plugins\n" + currentSadConfig.toString(2) + "\nin: " + configurationFilePath); } catch (IOException e) { logger.error("Failed to create temporary configuration file", e); return false; } ServerSocket s; Thread tempThread; int pluginCounter = 0; for (String pluginName : pluginsService.getPluginNames()) { pluginCounter++; logger.debug("Processing plugin " + pluginCounter + ": " + pluginName); pluginInfo = pluginsService.getPluginByName(pluginName); if (pluginInfo.isEmpty()) { logger.error("Plugin not found: " + pluginName); continue; } if (!pluginInfo.containsKey("paths")) { logger.error( "Plugin configuration must contain \'paths\'. Misconfigured plugin: " + pluginName); continue; } if (!pluginInfo.containsKey("pluginFolder")) { logger.error( "Plugin configuration must be loaded with pluginsService that fills in the \'pluginFolder\' field. Misconfigured plugin: " + pluginName); continue; } JSONObject pluginPaths = pluginInfo.getJSONObject("paths"); if (!pluginPaths.containsKey("jar")) { logger.error( "Plugin configuration must contain \'paths/jar\'. Misconfigured plugin: " + pluginName); continue; } if (!pluginPaths.containsKey("dependenciesFolder")) { logger.error( "Plugin configuration must contain \'paths/dependenciesFolder\'. Misconfigured plugin: " + pluginName); continue; } if (!pluginInfo.containsKey("pluginFolder")) { logger.error("Plugin configuration must contain \'pluginFolder\'. Misconfigured plugin: " + pluginName); continue; } // portNumber++; String jarPath = pluginPaths.getString("jar"); String dependenciesFolderPath = pluginPaths.getString("dependenciesFolder"); String pluginFolder = pluginInfo.getString("pluginFolder"); String port = null; try { s = new ServerSocket(0); port = Integer.toString(s.getLocalPort()); s.close(); } catch (IOException ex) { logger.error("Failed to assign a new free port", ex); throw new RuntimeException(ex); } String uuid = configurationService.getConfiguration().getEcc().getClientsUuuidSeed() + Integer.toHexString(pluginCounter); logger.debug("Using seeded UUID: " + uuid); logger.debug("Plugin jar path from configuration: " + jarPath + ", dependenciesFolderPath: " + dependenciesFolderPath); logger.debug("Plugin folder configuration: " + pathToPlugins); logger.debug("Socket port: " + port); logger.debug("ECC client UUID: " + uuid); String[] command = new String[] { "java", "-cp", pathToPlugins + fileSeparator + pluginFolder + fileSeparator + dependenciesFolderPath + fileSeparator + "*", "-jar", pathToPlugins + fileSeparator + pluginFolder + fileSeparator + jarPath, "ecc", configurationFilePath, port, uuid }; StringBuilder commandSb = new StringBuilder(); for (String c : command) { commandSb.append(c); commandSb.append(" "); } String commandAsString = commandSb.toString(); logger.debug("Launching ECC part of '" + pluginName + "' plugin with command: " + commandAsString + " on port: " + port); pluginNamesAndPorts.put(pluginName, port); try { Process p = Runtime.getRuntime().exec(command); tempThread = new Thread(new ProcessWatcher(p)); tempThread.start(); createdProcesses.add(p); } catch (Throwable ex) { logger.error("Failed to start ECC part of '" + pluginName + "' plugin", ex); result = false; } } } return result; }
From source file:ca.uhn.hunit.example.MllpHl7v2MessageSwapper.java
@Override public void run() { Socket socket = null;/*from www. java 2 s. c om*/ try { if (myPrintOutput) { System.out.println("Opening server socket on port " + 10201); } ServerSocket serverSocket = new ServerSocket(10201); socket = serverSocket.accept(); InputStream inputStream = socket.getInputStream(); inputStream = new BufferedInputStream(inputStream); MinLLPReader minLLPReader = new MinLLPReader(inputStream); Socket outSocket = null; if (myPrintOutput) { System.out.println("Accepting connection from " + socket.getInetAddress().getHostAddress()); } for (int i = 0; i < myIterations; i++) { String messageText; do { messageText = minLLPReader.getMessage(); Thread.sleep(250); } while (messageText == null); if (myPrintOutput) { System.out.println("Received message:\r\n" + messageText + "\r\n"); } MSH inboundHeader = (MSH) myParser.parse(messageText).get("MSH"); String controlId = inboundHeader.getMessageControlID().encode(); if (StringUtils.isNotBlank(controlId) && myControlIdsToIgnore.indexOf(controlId) > -1) { Message replyAck = DefaultApplication.makeACK(inboundHeader); new MinLLPWriter(socket.getOutputStream()).writeMessage(myParser.encode(replyAck)); } else { System.out.println("Ignoring message with control ID " + controlId); } for (Map.Entry<String, String> next : mySubstitutions.entrySet()) { messageText = messageText.replace(next.getKey(), next.getValue()); } if ((outSocket != null) && myAlwaysCreateNewOutboundConnection) { outSocket.close(); outSocket = null; } if (outSocket == null) { if (myPrintOutput) { System.out.println("Opening outbound connection to port " + 10200); } outSocket = new Socket(); outSocket.connect(new InetSocketAddress("localhost", 10200)); } if (myPrintOutput) { System.out.println("Sending message from port " + outSocket.getLocalPort() + ":\r\n" + messageText + "\r\n"); } new MinLLPWriter(outSocket.getOutputStream()).writeMessage(messageText); new MinLLPReader(outSocket.getInputStream()).getMessage(); } serverSocket.close(); socket.close(); myStopped = true; } catch (Exception e) { myStopped = true; e.printStackTrace(); } }
From source file:org.kde.kdeconnect.Backends.LanBackend.LanLink.java
private void sendPackageInternal(NetworkPackage np, final Device.SendPackageStatusCallback callback, PublicKey key) {//from w w w .ja va 2 s.co m if (session == null) { Log.e("KDE/sendPackage", "Not yet connected"); callback.sendFailure(new NotYetConnectedException()); return; } try { //Prepare socket for the payload final ServerSocket server; if (np.hasPayload()) { server = openTcpSocketOnFreePort(); JSONObject payloadTransferInfo = new JSONObject(); payloadTransferInfo.put("port", server.getLocalPort()); np.setPayloadTransferInfo(payloadTransferInfo); } else { server = null; } //Encrypt if key provided if (key != null) { np = np.encrypt(key); } //Send body of the network package WriteFuture future = session.write(np.serialize()); future.awaitUninterruptibly(); if (!future.isWritten()) { //Log.e("KDE/sendPackage", "!future.isWritten()"); callback.sendFailure(future.getException()); return; } //Send payload if (server != null) { OutputStream socket = null; try { //Wait a maximum of 10 seconds for the other end to establish a connection with our socket, close it afterwards server.setSoTimeout(10 * 1000); socket = server.accept().getOutputStream(); Log.i("KDE/LanLink", "Beginning to send payload"); byte[] buffer = new byte[4096]; int bytesRead; long progress = 0; InputStream stream = np.getPayload(); while ((bytesRead = stream.read(buffer)) != -1) { //Log.e("ok",""+bytesRead); progress += bytesRead; socket.write(buffer, 0, bytesRead); if (np.getPayloadSize() > 0) { callback.sendProgress((int) (progress / np.getPayloadSize())); } } socket.flush(); stream.close(); Log.i("KDE/LanLink", "Finished sending payload (" + progress + " bytes written)"); } catch (Exception e) { Log.e("KDE/sendPackage", "Exception: " + e); callback.sendFailure(e); return; } finally { if (socket != null) { try { socket.close(); } catch (Exception e) { } } try { server.close(); } catch (Exception e) { } } } callback.sendSuccess(); } catch (Exception e) { if (callback != null) { callback.sendFailure(e); } } finally { //Make sure we close the payload stream, if any InputStream stream = np.getPayload(); try { stream.close(); } catch (Exception e) { } } }
From source file:org.apache.htrace.impl.HTracedProcess.java
private HTracedProcess(Builder builder) throws Exception { this.htracedPath = Paths.get("target", "..", "go", "build", "htraced").toFile(); if (!this.htracedPath.exists()) { throw new RuntimeException("No htraced binary exists at " + this.htracedPath); }//from w w w . j av a 2s . c o m this.dataDir = new DataDir(); // Create a notifier socket bound to a random port. ServerSocket listener = new ServerSocket(0); boolean success = false; Process process = null; HttpClient http = null; try { // Use a random port for the web address. No 'scheme' yet. String random = builder.host + ":0"; String logPath = new File(dataDir.get(), "log.txt").getAbsolutePath(); // Pass cmdline args to htraced to it uses our test dir for data. ProcessBuilder pb = new ProcessBuilder(htracedPath.getAbsolutePath(), "-Dlog.level=TRACE", "-Dlog.path=" + logPath, "-Dweb.address=" + random, "-Dhrpc.address=" + random, "-Ddata.store.clear=true", "-Dstartup.notification.address=localhost:" + listener.getLocalPort(), "-Ddata.store.directories=" + dataDir.get().getAbsolutePath()); // Set HTRACED_CONF_DIR to the temporary directory we just created, to // ensure that it doesn't pull in any other configuration file that might // be on this test machine. Map<String, String> env = pb.environment(); env.put("HTRACED_CONF_DIR", dataDir.get().getAbsolutePath()); // Remove any HTRACED_WEB_DIR variable that might be set, to ensure that // we use the default value (which finds the local web files by relative // path). env.remove("HTRACED_WEB_DIR"); pb.redirectErrorStream(true); // Inherit STDERR/STDOUT i/o; dumps on console for now. Can add logs later. pb.inheritIO(); pb.directory(dataDir.get()); //assert pb.redirectInput() == Redirect.PIPE; //assert pb.redirectOutput().file() == dataDir; process = pb.start(); assert process.getInputStream().read() == -1; StartupNotificationData data = readStartupNotification(listener); httpAddr = data.httpAddr; hrpcAddr = data.hrpcAddr; LOG.info("Started htraced process " + data.processId + " with http " + "address " + data.httpAddr + ", logging to " + logPath); http = RestBufferManager.createHttpClient(60000L, 60000L); http.start(); success = true; } finally { if (!success) { // Clean up after failure if (process != null) { process.destroy(); process = null; } if (http != null) { http.stop(); } } delegate = process; listener.close(); httpClient = http; } }
From source file:com.jredrain.startup.Bootstrap.java
private void await() throws Exception { // Negative values - don't wait on port - redrain is embedded or we just don't like ports if (port == -2) { return;/*from w w w. j a v a2s. c o m*/ } if (port == -1) { try { awaitThread = Thread.currentThread(); while (!stopAwait) { try { Thread.sleep(10000); } catch (InterruptedException ex) { // continue and check the flag } } } finally { awaitThread = null; } return; } // Set up a server socket to wait on try { awaitSocket = new ServerSocket(RedrainProperties.getInt("redrain.shutdown")); } catch (IOException e) { logger.error("[redrain] agent .await: create[{}] ", RedrainProperties.getInt("redrain.shutdown"), e); return; } try { awaitThread = Thread.currentThread(); // Loop waiting for a connection and a valid command while (!stopAwait) { ServerSocket serverSocket = awaitSocket; if (serverSocket == null) { break; } // Wait for the next connection Socket socket = null; StringBuilder command = new StringBuilder(); try { InputStream stream; long acceptStartTime = System.currentTimeMillis(); try { socket = serverSocket.accept(); socket.setSoTimeout(10 * 1000); // Ten seconds stream = socket.getInputStream(); } catch (SocketTimeoutException ste) { // This should never happen but bug 56684 suggests that // it does. logger.warn("[redrain] agentServer accept.timeout", Long.valueOf(System.currentTimeMillis() - acceptStartTime), ste); continue; } catch (AccessControlException ace) { logger.warn("[redrain] agentServer .accept security exception: {}", ace.getMessage(), ace); continue; } catch (IOException e) { if (stopAwait) { break; } logger.error("[redrain] agent .await: accept: ", e); break; } // Read a set of characters from the socket int expected = 1024; // Cut off to avoid DoS attack while (expected < shutdown.length()) { if (random == null) { random = new Random(); } expected += (random.nextInt() % 1024); } while (expected > 0) { int ch = -1; try { ch = stream.read(); } catch (IOException e) { logger.warn("[redrain] agent .await: read: ", e); ch = -1; } if (ch < 32) // Control character or EOF terminates loop break; command.append((char) ch); expected--; } } finally { try { if (socket != null) { socket.close(); } } catch (IOException e) { } } boolean match = command.toString().equals(shutdown); if (match) { break; } else { logger.warn("[redrain] agent .await: Invalid command '" + command.toString() + "' received"); } } } finally { ServerSocket serverSocket = awaitSocket; awaitThread = null; awaitSocket = null; // Close the server socket and return if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { // Ignore } } } }
From source file:org.opencron.agent.Bootstrap.java
private void await() throws Exception { // Negative values - don't wait on port - opencron is embedded or we just don't like ports if (port == -2) { return;/*from w w w . j av a 2s . c o m*/ } if (port == -1) { try { awaitThread = Thread.currentThread(); while (!stopAwait) { try { Thread.sleep(10000); } catch (InterruptedException ex) { // continue and check the flag } } } finally { awaitThread = null; } return; } // Set up a server socket to wait on try { awaitSocket = new ServerSocket(AgentProperties.getInt("opencron.shutdown")); } catch (IOException e) { logger.error("[opencron] agent .await: create[{}] ", AgentProperties.getInt("opencron.shutdown"), e); return; } try { awaitThread = Thread.currentThread(); // Loop waiting for a connection and a valid command while (!stopAwait) { ServerSocket serverSocket = awaitSocket; if (serverSocket == null) { break; } // Wait for the next connection Socket socket = null; StringBuilder command = new StringBuilder(); try { InputStream stream; long acceptStartTime = System.currentTimeMillis(); try { socket = serverSocket.accept(); socket.setSoTimeout(10 * 1000); // Ten seconds stream = socket.getInputStream(); } catch (SocketTimeoutException ste) { // This should never happen but bug 56684 suggests that // it does. logger.warn("[opencron] agentServer accept.timeout", Long.valueOf(System.currentTimeMillis() - acceptStartTime), ste); continue; } catch (AccessControlException ace) { logger.warn("[opencron] agentServer .accept security exception: {}", ace.getMessage(), ace); continue; } catch (IOException e) { if (stopAwait) { break; } logger.error("[opencron] agent .await: accept: ", e); break; } // Read a set of characters from the socket int expected = 1024; // Cut off to avoid DoS attack while (expected < shutdown.length()) { if (random == null) { random = new Random(); } expected += (random.nextInt() % 1024); } while (expected > 0) { int ch = -1; try { ch = stream.read(); } catch (IOException e) { logger.warn("[opencron] agent .await: read: ", e); ch = -1; } if (ch < 32) // Control character or EOF terminates loop break; command.append((char) ch); expected--; } } finally { try { if (socket != null) { socket.close(); } } catch (IOException e) { } } boolean match = command.toString().equals(shutdown); if (match) { break; } else { logger.warn("[opencron] agent .await: Invalid command '" + command.toString() + "' received"); } } } finally { ServerSocket serverSocket = awaitSocket; awaitThread = null; awaitSocket = null; // Close the server socket and return if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { // Ignore } } } }