List of usage examples for java.net ServerSocket ServerSocket
public ServerSocket(int port) throws IOException
From source file:com.hcb.uiautomator.server.SocketServer.java
/** * Constructor/* w ww . j a v a 2s .c om*/ * * @param port * @throws Exception */ public SocketServer(int port) throws Exception { keepListening = true; executor = new AndroidCommandExecutor(); try { server = new ServerSocket(port); Logger.debug("Socket opened on port " + port); } catch (final IOException e) { throw new Exception("Could not start socket server listening on " + port); } }
From source file:jdroidremote.ServerFrame.java
public void initEventDriven() { jbtRunServer.addActionListener(new ActionListener() { @Override// ww w .j av a 2 s . c o m public void actionPerformed(ActionEvent e) { new Thread(new Runnable() { @Override public void run() { try { serverSocket = new ServerSocket(5005); System.out.println("Server is running..."); clientSocket = serverSocket.accept(); dis = new DataInputStream(clientSocket.getInputStream()); dos = new DataOutputStream(clientSocket.getOutputStream()); System.out.println( "some device connected us from address: " + clientSocket.getInetAddress()); thReceiveMouseCoords.start(); thStartMonitoring.start(); } catch (IOException ex) { Logger.getLogger(ServerFrame.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); thReceiveMouseCoords = new Thread(new Runnable() { @Override public void run() { System.out.println("START RECEIVING COORDS............."); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); double width = screenSize.getWidth(); double height = screenSize.getHeight(); while (1 == 1) { try { String receivedStr = dis.readUTF(); if (receivedStr.contains("left_click")) { robot.mousePress(KeyEvent.BUTTON1_DOWN_MASK); robot.mouseRelease(KeyEvent.BUTTON1_DOWN_MASK); } else if (receivedStr.contains("right_click")) { robot.mousePress(KeyEvent.BUTTON3_DOWN_MASK); robot.mouseRelease(KeyEvent.BUTTON3_DOWN_MASK); } else if (receivedStr.contains("coords")) { System.out.println(receivedStr); String[] mouseCoords = receivedStr.split(":"); int x = (int) (Integer.parseInt(mouseCoords[0]) * width / 100); int y = (int) (Integer.parseInt(mouseCoords[1]) * height / 100); robot.mouseMove(x, y); } else { String[] dataArr = receivedStr.split("-"); typeCharacter(dataArr[1]); } } catch (IOException ex) { Logger.getLogger(ServerFrame.class.getName()).log(Level.SEVERE, null, ex); } } } }); } }); }
From source file:com.baidu.terminator.manager.service.LinkServiceImpl.java
@Override public boolean isPortAvailable(int port) { int count = linkMapper.countValidPort(port); if (count >= 1) { return false; } else {//w w w . j ava 2s . c o m try { ServerSocket s = new ServerSocket(port); s.close(); } catch (IOException e) { return false; } } return true; }
From source file:eu.eubrazilcc.lvl.core.NetworkingUtilsTest.java
@Test public void test() { System.out.println("NetworkingUtilsTest.test()"); try {/*ww w.j av a 2 s .c om*/ // check IP address discover final String address = getInet4Address(); assertThat("host IP address is not null", address, notNullValue()); assertThat("Host IP address is not empty", isNotBlank(address)); // check port availability final int port = 33435; assertThat("port " + port + " is available", isPortAvailable(port), equalTo(true)); try (final ServerSocket socket = new ServerSocket(port)) { assertThat("port " + port + " is unavailable", isPortAvailable(port), equalTo(false)); } } catch (Exception e) { e.printStackTrace(System.err); fail("NetworkingUtilsTest.test() failed: " + e.getMessage()); } finally { System.out.println("NetworkingUtilsTest.test() has finished"); } }
From source file:edu.umn.msi.tropix.transfer.http.server.embedded.JettyServer.java
private boolean isPortFree(final int port) { boolean isPortFree = true; ServerSocket socket = null;/*from ww w.j a v a 2s .c om*/ try { socket = new ServerSocket(port); } catch (final IOException e) { isPortFree = false; } finally { // Close socket quitely. if (socket != null) { try { socket.close(); } catch (final IOException io) { LOG.debug("Failed to close socket " + socket); } } } return isPortFree; }
From source file:TestHTTPSource.java
private static int findFreePort() throws IOException { ServerSocket socket = new ServerSocket(0); int port = socket.getLocalPort(); socket.close();//w w w . j a v a 2 s . co m return port; }
From source file:org.apache.ambari.common.util.PidFile.java
public void init(int port) throws IOException { String pidLong = ManagementFactory.getRuntimeMXBean().getName(); String[] items = pidLong.split("@"); String pid = items[0];//from w w w .j a va 2 s . c om String chukwaPath = System.getProperty("AMBARI_HOME"); StringBuffer pidFilesb = new StringBuffer(); String pidDir = System.getenv("AMBARI_PID_DIR"); if (pidDir == null) { pidDir = chukwaPath + File.separator + "var" + File.separator + "run"; } pidFilesb.append(pidDir).append(File.separator).append(name).append(".pid"); try { serverSocket = new ServerSocket(port); File existsFile = new File(pidDir); if (!existsFile.exists()) { boolean success = (new File(pidDir)).mkdirs(); if (!success) { throw (new IOException()); } } File pidFile = new File(pidFilesb.toString()); pidFileOutput = new FileOutputStream(pidFile); pidFileOutput.write(pid.getBytes()); pidFileOutput.flush(); log.debug("Initlization succeeded..."); } catch (IOException ex) { System.out.println("Initialization failed: can not write pid file to " + pidFilesb); log.error("Initialization failed..."); log.error(ex.getMessage()); System.exit(-1); throw ex; } }
From source file:de.th.wildau.dsc.sne.webserver.WebServer.java
/** * Web server / main constructor./* w w w . j av a 2 s.c o m*/ * * @param startArguments */ public WebServer(String[] startArguments) { loadConfiguration(startArguments); Log.debug(Configuration.getInstance().toString()); Log.debug("Information about the OS: " + System.getProperty("os.name") + " - " + System.getProperty("os.version") + " - " + System.getProperty("os.arch")); if (Configuration.getConfig().getProxyHost() != null) { Log.debug("setup proxy configuration"); System.setProperty("http.proxyHost", Configuration.getConfig().getProxyHost()); System.setProperty("http.proxyPort", String.valueOf(Configuration.getConfig().getProxyPort())); } Log.debug("find supported scripting languages"); supportedScriptLanguages = Collections.unmodifiableList(ScriptExecutor.getSupportedScriptLanguages()); Log.debug("Supported Script Languages " + Arrays.toString(supportedScriptLanguages.toArray())); Log.info("instantiating web server"); try { ServerSocket server = new ServerSocket(Configuration.getConfig().getServerPort()); Log.debug("bound port " + Configuration.getConfig().getServerPort()); int corePoolSize = Runtime.getRuntime().availableProcessors(); int maxPoolSize = (2 * corePoolSize) + 1; Log.debug("core/max pool size: " + corePoolSize + "/" + maxPoolSize); LinkedBlockingQueue<Runnable> workerQueue = new LinkedBlockingQueue<Runnable>(); long keepAliveTime = 30; /* * keepAliveTime - If the pool currently has more than corePoolSize * threads, excess threads will be terminated if they have been idle * for more than the keepAliveTime. */ ThreadPoolExecutor threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, workerQueue); threadPool.prestartAllCoreThreads(); Socket socket = null; while (true) { try { socket = server.accept(); Log.info(socket.getInetAddress().getHostName() + " client request"); threadPool.execute(new HttpHandler(socket)); Log.debug("current threads: " + threadPool.getActiveCount()); } catch (final IOException ex) { Log.error("Connection failed!", ex); } catch (final RejectedExecutionException ex) { // XXX [sne] RejectedExecutionException // http://stackoverflow.com/questions/1519725/why-does-executors-newcachedthreadpool-throw-java-util-concurrent-rejectedexecut // http://www.javamex.com/tutorials/threads/thread_pools_queues.shtml // http://stackoverflow.com/questions/2001086/how-to-make-threadpoolexecutors-submit-method-block-if-it-is-saturated Log.error("RejectedExecutionException", ex); socket.close(); } catch (final Exception ex) { Log.fatal("Unknown error!", ex); } } } catch (final IOException ex) { Log.fatal("Can not start the server!", ex); System.err.println("Can not start the server! " + ex.getMessage()); } catch (final Exception ex) { Log.fatal("Unknown error!", ex); } }
From source file:fm.last.moji.FakeMogileFsServer.java
private void startTracker(final Builder builder) throws IOException { trackerSocket = new ServerSocket(0); trackerThread = new TrackerServer(builder.conversation); trackerThread.start();/*from ww w. j ava 2s. c om*/ log.info("Tracker server running on: {}", getAddressAsString()); }
From source file:com.topekalabs.bigmachine.lib.app.ContinuationSerializationTest.java
@Ignore @Test/*from w w w . j av a 2 s.c o m*/ public void networkSerializationTest() throws Exception { Socket outputSocket = null; ServerSocket inputSocket = null; outputSocket = new Socket("localhost", TEST_SOCKET); inputSocket = new ServerSocket(TEST_SOCKET); Continuation c = Continuation.startWith(new SimpleContinuationRunnable()); Kryo kryo = new Kryo(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Output output = new Output(bos); kryo.writeObject(output, c); }