List of usage examples for java.net ServerSocket ServerSocket
public ServerSocket(int port) throws IOException
From source file:AvailablePortFinder.java
/** * Returns the {@link Set} of currently avaliable port numbers ({@link Integer}) * between the specified port range./* w w w .j a va 2 s. c om*/ * * @throws IllegalArgumentException if port range is not between * {@link #MIN_PORT_NUMBER} and {@link #MAX_PORT_NUMBER} or * <code>fromPort</code> if greater than <code>toPort</code>. */ public static Set<Integer> getAvailablePorts(int fromPort, int toPort) { if (fromPort < MIN_PORT_NUMBER || toPort > MAX_PORT_NUMBER || fromPort > toPort) { throw new IllegalArgumentException("Invalid port range: " + fromPort + " ~ " + toPort); } Set<Integer> result = new TreeSet<Integer>(); for (int i = fromPort; i <= toPort; i++) { ServerSocket s = null; try { s = new ServerSocket(i); result.add(new Integer(i)); } catch (IOException e) { } finally { if (s != null) { try { s.close(); } catch (IOException e) { /* should not be thrown */ } } } } return result; }
From source file:info.varden.irclinqed.dcc.FileSendThread.java
@Override public void onIPSelected(String ipAddress) { try {//from w w w .j a v a2s . com if (!this.file.exists()) { return; } this.server = new ServerSocket(0); this.server.setSoTimeout(60000); DCCRequestPacket packet = null; String filename = this.file.getName(); if (filename.split(" ").length > 1) { filename = "\"" + filename + "\""; } if (this.thread instanceof IRCThread) { packet = new DCCRequestPacket(this.il, (IRCThread) this.thread, this.target, DCCType.SEND, filename, ipAddress, server.getLocalPort(), this.totalSize); } else if (this.thread instanceof DCCThread) { VirtualIRCThread thrd = new VirtualIRCThread(this.il, (DCCThread) this.thread); packet = new DCCRequestPacket(this.il, thrd, this.target, DCCType.SEND, filename, ipAddress, server.getLocalPort(), this.totalSize); } else { this.server.close(); return; } packet.send(); if (this.cancel) { this.server.close(); return; } this.message = "Waiting for connection..."; Socket s = this.server.accept(); this.overlay.unload(); this.gfp = new GuiFileProgress(this.il, this); this.il.guiQueue.add(this.gfp); InputStream i = new FileInputStream(this.file); this.cos = new CountingOutputStream(s.getOutputStream()); byte[] buff = new byte[1024]; int k = -1; while ((k = i.read(buff)) > -1 && !this.cancel) { this.cos.write(buff, 0, k); s.getInputStream().read(new byte[4]); } s.shutdownInput(); s.shutdownOutput(); s.close(); this.server.close(); i.close(); this.gfp.unload(); } catch (SocketTimeoutException e) { this.overlay.unload(); Util.extractUtil(this.thread).writeToChat(MessageType.DCC_ERROR, "File send timed out."); } catch (IOException e) { e.printStackTrace(); } this.overlay.unload(); }
From source file:com.deicos.lince.Initializer.java
private boolean isPortFree(int port) { boolean isPortTaken = false; ServerSocket socket = null;/*from w w w . ja v a2 s. c o m*/ try { socket = new ServerSocket(port); } catch (IOException e) { isPortTaken = true; } finally { if (socket != null) try { socket.close(); } catch (IOException e) { /* e.printStackTrace(); */ } } return isPortTaken; }
From source file:fr.fastconnect.factory.tibco.bw.maven.bwengine.AbstractServiceEngineMojo.java
public static boolean available(int port, int minPort, int maxPort) { if (port < minPort || port > maxPort || port > 65535) { throw new IllegalArgumentException("Invalid start port: " + port); }/* w ww.ja va 2s . c om*/ 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:opendial.modules.core.RemoteConnector.java
/** * A server socket is created, using an arbitrary open port (NB: the port can be * read in the "About" page in the GUI). * // ww w . j a va 2s.c o m * @param system the local dialogue system * @throws DialException if the server socket could not be opened */ public RemoteConnector(DialogueSystem system) throws DialException { this.system = system; try { local = new ServerSocket(0); new Thread(() -> readContent()).start(); } catch (IOException e) { throw new DialException("cannot initialise remote connector: " + e); } }
From source file:to.sven.androidrccar.host.communication.impl.SocketConnector.java
/** * Start to listen on the {@link ServerSocket}. *///from w w w . j av a 2s.co m @Override protected AsyncTaskResult<Socket> doInBackground(Object... params) { try { ServerSocket serverSocket = new ServerSocket(port); Socket socket = serverSocket.accept(); serverSocket.close(); return new AsyncTaskResult<Socket>(socket); } catch (Exception ex) { return new AsyncTaskResult<Socket>(ex); } }
From source file:org.apache.flink.streaming.api.functions.sink.SocketClientSinkTest.java
@Test public void testSinkAutoFlush() throws Exception { final ServerSocket server = new ServerSocket(0); final int port = server.getLocalPort(); final SocketClientSink<String> simpleSink = new SocketClientSink<>(host, port, simpleSchema, 0, true); simpleSink.open(new Configuration()); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); Thread sinkRunner = new Thread("Test sink runner") { @Override/* ww w . ja v a 2 s . c om*/ public void run() { try { // need two messages here: send a fin to cancel the client state:FIN_WAIT_2 while the server is CLOSE_WAIT simpleSink.invoke(TEST_MESSAGE + '\n'); } catch (Throwable t) { error.set(t); } } }; sinkRunner.start(); Socket sk = server.accept(); BufferedReader rdr = new BufferedReader(new InputStreamReader(sk.getInputStream())); String value = rdr.readLine(); sinkRunner.join(); simpleSink.close(); server.close(); if (error.get() != null) { Throwable t = error.get(); t.printStackTrace(); fail("Error in spawned thread: " + t.getMessage()); } assertEquals(TEST_MESSAGE, value); }
From source file:it.crs4.pydoop.pipes.Application.java
/** * Start the child process to handle the task for us. * @param conf the task's configuration//from w ww. ja v a 2s . c o m * @param recordReader the fake record reader to update progress with * @param output the collector to send output to * @param reporter the reporter for the task * @param outputKeyClass the class of the output keys * @param outputValueClass the class of the output values * @throws IOException * @throws InterruptedException */ Application(JobConf conf, RecordReader<FloatWritable, NullWritable> recordReader, OutputCollector<K2, V2> output, Reporter reporter, Class<? extends K2> outputKeyClass, Class<? extends V2> outputValueClass) throws IOException, InterruptedException { serverSocket = new ServerSocket(0); Map<String, String> env = new HashMap<String, String>(); // add TMPDIR environment variable with the value of java.io.tmpdir env.put("TMPDIR", System.getProperty("java.io.tmpdir")); env.put(Submitter.PORT, Integer.toString(serverSocket.getLocalPort())); TaskAttemptID taskid = TaskAttemptID.forName(conf.get(MRJobConfig.TASK_ATTEMPT_ID)); // get the task's working directory String workDir = LocalJobRunner.getLocalTaskDir(conf.getUser(), taskid.getJobID().toString(), taskid.getTaskID().toString(), false); //Add token to the environment if security is enabled Token<JobTokenIdentifier> jobToken = TokenCache.getJobToken(conf.getCredentials()); // This password is used as shared secret key between this application and // child pipes process byte[] password = jobToken.getPassword(); String localPasswordFile = new File(workDir, "jobTokenPassword").getAbsolutePath(); writePasswordToLocalFile(localPasswordFile, password, conf); env.put("hadoop.pipes.shared.secret.location", localPasswordFile); List<String> cmd = new ArrayList<String>(); String interpretor = conf.get(Submitter.INTERPRETOR); if (interpretor != null) { cmd.add(interpretor); } String executable = DistributedCache.getLocalCacheFiles(conf)[0].toString(); if (!(new File(executable).canExecute())) { // LinuxTaskController sets +x permissions on all distcache files already. // In case of DefaultTaskController, set permissions here. FileUtil.chmod(executable, "u+x"); } cmd.add(executable); // wrap the command in a stdout/stderr capture // we are starting map/reduce task of the pipes job. this is not a cleanup // attempt. File stdout = TaskLog.getTaskLogFile(taskid, false, TaskLog.LogName.STDOUT); File stderr = TaskLog.getTaskLogFile(taskid, false, TaskLog.LogName.STDERR); long logLength = TaskLog.getTaskLogLength(conf); cmd = TaskLog.captureOutAndError(null, cmd, stdout, stderr, logLength, false); process = runClient(cmd, env); clientSocket = serverSocket.accept(); String challenge = getSecurityChallenge(); String digestToSend = createDigest(password, challenge); String digestExpected = createDigest(password, digestToSend); handler = new OutputHandler<K2, V2>(output, reporter, recordReader, digestExpected); K2 outputKey = (K2) ReflectionUtils.newInstance(outputKeyClass, conf); V2 outputValue = (V2) ReflectionUtils.newInstance(outputValueClass, conf); downlink = new BinaryProtocol<K1, V1, K2, V2>(clientSocket, handler, outputKey, outputValue, conf); downlink.authenticate(digestToSend, challenge); waitForAuthentication(); LOG.debug("Authentication succeeded"); downlink.start(); downlink.setJobConf(conf); }
From source file:eu.smeny.jpapercut.smtp.MailServer.java
private void openServerSocket() { try {//from www.j a va 2s.c om socket = new ServerSocket(port); logger.info("Socket opened successfully on port " + port); running = true; } catch (IOException ioe) { logger.error("Error while opening socket on port " + port, ioe); } }
From source file:eu.eubrazilcc.lvl.core.util.NetworkingUtils.java
public static final boolean isPortAvailable(final int port) throws IllegalArgumentException { checkArgument(USER_PORTS_16_BITS.contains(port), "Invalid start port: " + port); try (final ServerSocket ss = new ServerSocket(port); final DatagramSocket ds = new DatagramSocket(port)) { ss.setReuseAddress(true);//from w w w .j ava 2 s.c om ds.setReuseAddress(true); return true; } catch (IOException ignore) { } return false; }