@Test public void printSockets() throws IOException { ServerSocket ss = new ServerSocket(); ss.bind(sock(5000)); Socket s1 = new Socket(); Socket s2 = new Socket(); s1.connect(sock(5000)); s2.connect(sock(5000)); ss.close(); s1.close(); // s2 remains unclosed HeapImage hi = HeapUnit.captureHeap(); for(HeapInstance i: hi.instances(SocketImpl.class)) { // fd field in SocketImpl class is nullified when socket gets closed boolean open = i.value("fd") != null; System.out.println(i.rehydrate() + (open ? " - open" : " - closed")); } }
/** * Creates a new Server using TLS */ public TLSServer(final byte[] keyStore, final char[] keyStorePassword, final String keyStoreType) throws IOException { super(new ServerImpl( new ServerSocketFactory() { @Override public ServerSocket getServerSocket(final int port) throws Exception { return new TLSBuilder() .withPort(port) .withKeyStore(keyStoreType, new ByteArrayInputStream(keyStore), keyStorePassword) .buildServerSocket(); } }, new ClientFactory() { @Override public Client getClient() { return new TLSClient(); } } )); }
@Test public void testCloseServerSocketThrowsIOException() throws IOException { final ServerSocket mockServerSocket = mockContext.mock(ServerSocket.class, "closeServerSocketThrowsIOExceptionTest"); mockContext.checking(new Expectations() { { oneOf(mockServerSocket).close(); will(throwException(new IOException("test"))); } }); try { assertFalse(SocketUtils.close(mockServerSocket)); } catch (Throwable t) { fail("Calling close on a ServerSocket using SocketUtils threw an unexpected Throwable (" + t + ")!"); } }
/** * Starts the server * @return Server This Server */ public final Server start() { try { boolean port_valid = checkPortAvailable(port); if(port_valid) { stopThread(thread_receive); serversocket = new ServerSocket(port); instant_started = Instant.now(); started = true; registerServerPort(port); StaticStandard.log("[SERVER] Started server on port: " + port); resetThreadReceive(); startThread(thread_receive); timer.start(); } else { instant_started = null; StaticStandard.logErr("[SERVER] Failed starting server on port: " + port + ", port already binded"); } } catch (Exception ex) { instant_started = null; StaticStandard.logErr("[SERVER] Error while starting server: " + ex, ex); } return this; }
@Before public void setUp(TestContext context) throws IOException { vertx = Vertx.vertx(); // Pick an available and random ServerSocket socket = new ServerSocket(0); port = socket.getLocalPort(); socket.close(); DeploymentOptions options = new DeploymentOptions() .setConfig(new JsonObject() .put("HTTP_PORT", port) .put("url", "jdbc:hsqldb:mem:test?shutdown=true") .put("driver_class", "org.hsqldb.jdbcDriver") ); vertx.deployVerticle(MyFirstVerticle.class.getName(), options, context.asyncAssertSuccess()); }
public static void main(String argv[]) throws Exception { AutoRunFromConsole.runYourselfInConsole(true); String clientSentence; ServerSocket welcomeSocket = new ServerSocket(4405); System.out.println("Logger started!"); PrintWriter outPrinter = new PrintWriter("tcp_log.txt"); while (true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); while (true) { try { clientSentence = inFromClient.readLine(); if (clientSentence == null) break; System.out.println(clientSentence); outPrinter.println(clientSentence); outPrinter.flush(); } catch (Exception e) { break; } } System.out.println("Connection closed."); } }
public ServerSocket createServerSocket(int port) throws IOException { ServerSocket sock = null; if ("".equals(bindAddress)) { sock = socketCreator.createServerSocket(port, this.backlog); } else { sock = socketCreator.createServerSocket(port, this.backlog, InetAddressUtil.toInetAddress(this.bindAddress)); } if (logger.isDebugEnabled()) { logger.debug( "MX4JServerSocketFactory RMIServerSocketFactory, INetAddress {}, LocalPort {}, LocalSocketAddress {}", sock.getInetAddress(), sock.getLocalPort(), sock.getLocalSocketAddress()); } return sock; }
@Override public void run() { try { server.setServerSocket(new ServerSocket(server.getPort())); if (server.getTimeout() > 0) { server.getServerSocket().setSoTimeout(server.getTimeout()); } server.setServerRunning(true); server.onServerStarted(); while (server.isServerRunning()) { Socket socket = server.getServerSocket().accept(); ListenToClient client = new ListenToClient(this, socket); client.setClientId(server.getNextUniqeID()); server.getClients().add(client); client.startListener(); } } catch (Exception e) { e.printStackTrace(); } stopServer(); server.onServerStopped(); }
public void startHttpServer() { if (isServerAlive()) { return; } for (int port : new int[]{61593, 41123, 43387, 39083, 24423, 16834, 9289, 8452, 6217, 5300, 4118, 3787, 2998, 0}) { try { ServerSocket localServer = new ServerSocket(port); int localPort = localServer.getLocalPort(); if (localPort <= 0) { continue; } mMainThread = new MainThread(localServer); mMainThread.start(); break; } catch (IOException e) { e.printStackTrace(); } } }
public Acceptor(ServerSocket serverSocket, URI uri) { socket = serverSocket; target = uri; pause.set(new CountDownLatch(0)); try { socket.setSoTimeout(ACCEPT_TIMEOUT_MILLIS); } catch (SocketException e) { e.printStackTrace(); } }
protected void bind() throws IOException { // allocate an unbound server socket channel serverChannel = ServerSocketChannel.open(); // Get the associated ServerSocket to bind it with ServerSocket serverSocket = serverChannel.socket(); // create a new Selector for use below synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 this.selector.set(Selector.open()); } // set the port the server channel will listen to //serverSocket.bind(new InetSocketAddress(getBind(), getTcpListenPort())); bind(serverSocket,getPort(),getAutoBind()); // set non-blocking mode for the listening socket serverChannel.configureBlocking(false); // register the ServerSocketChannel with the Selector serverChannel.register(this.selector.get(), SelectionKey.OP_ACCEPT); //set up the datagram channel if (this.getUdpPort()>0) { datagramChannel = DatagramChannel.open(); configureDatagraChannel(); //bind to the address to avoid security checks bindUdp(datagramChannel.socket(),getUdpPort(),getAutoBind()); } }
public MockServerThread(ServerSocket serverSocket, Deque<ImapInteraction> interactions, CountDownLatch waitForConnectionClosed, CountDownLatch waitForAllExpectedCommands, Logger logger, KeyStoreProvider keyStoreProvider) { super("MockImapServer"); this.serverSocket = serverSocket; this.interactions = interactions; this.waitForConnectionClosed = waitForConnectionClosed; this.waitForAllExpectedCommands = waitForAllExpectedCommands; this.logger = logger; this.keyStoreProvider = keyStoreProvider; }
/** * Closes all of the opened sockets */ protected void closeAllSockets_do(boolean logWarning) { int i = 0; for (DatagramSocket datagramsocket : this.socketList) { if (this.closeSocket(datagramsocket, false)) { ++i; } } this.socketList.clear(); for (ServerSocket serversocket : this.serverSocketList) { if (this.closeServerSocket_do(serversocket, false)) { ++i; } } this.serverSocketList.clear(); if (logWarning && 0 < i) { this.logWarning("Force closed " + i + " sockets"); } }
public static void main(String[] args) throws Exception { try (ServerSocket ss = new ServerSocket(0)) { runTest(OutputStreamGetter.class, ss); runTest(InputStreamGetter.class, ss); } if (failed) throw new RuntimeException("Failed, check output"); }
public ServerThread(int port, ServerListener s){ try { this.listener = s; server = new ServerSocket(port); this.port = port; this.start(); } catch (IOException e) { if(e instanceof BindException){ StatusPrinter.print("ERROR", "Server already running? [port:"+port+"]", ServerThread.class); if(listener!=null){listener.onBindException();} }else{ e.printStackTrace(); } } }
/** * start forwarding * @param pDevice * @param pPortNumber * @param pBaudRate * @throws Exception if something goes wrong */ public void forward(String pDevice, int pPortNumber, int pBaudRate) throws Exception { prepare(pDevice,pBaudRate); ConnectionForwarder forwarder=new ConnectionForwarder(); // elm.initOBD2(); // elm.initOBD2(); forwarder.setLog(con.getLog()); forwarder.createServerSocket(pPortNumber); forwarder.startServer(con); ServerSocket serverSocket = forwarder.getServerSocket(); Socket clientSocket=new Socket("localhost",serverSocket.getLocalPort()); forwarder.getServerThread().join(); }
/** * Create a new ServerSocket that will not accept SSLv3 connections, * but will accept TLSv1.x connections. */ protected ServerSocket newServerSocket(String host, int port,int backlog) throws IOException { SSLServerSocket socket = (SSLServerSocket) super.newServerSocket(host, port, backlog); ArrayList<String> nonSSLProtocols = new ArrayList<String>(); for (String p : socket.getEnabledProtocols()) { if (!p.contains("SSLv3")) { nonSSLProtocols.add(p); } } socket.setEnabledProtocols(nonSSLProtocols.toArray( new String[nonSSLProtocols.size()])); return socket; }
@Override public void run() { try { serverSocket = new ServerSocket(socketServerPORT); isOpen = true; WritableMap eventParams = Arguments.createMap(); sendEvent(mReactContext, event_connect, eventParams); while (isOpen) { Socket socket = serverSocket.accept(); count++; mClients.put(socket.getPort(), socket); eventParams = Arguments.createMap(); eventParams.putInt("id", socket.getPort()); sendEvent(mReactContext, event_clientConnect, eventParams); Log.d(eTag, "#" + count + " from " + socket.getInetAddress() + ":" + socket.getPort()); Thread socketServerReplyThread = new Thread(new SocketServerReplyThread(socket)); socketServerReplyThread.start(); } } catch (IOException e) { handleIOException(e); } }
@BeforeClass public static void setup() throws IOException { listenSocket = new ServerSocket(); listenSocket.bind(null); bindAddr = NetUtils.getHostPortString( (InetSocketAddress)listenSocket.getLocalSocketAddress()); redirectResponse = "HTTP/1.1 307 Redirect\r\n" + "Location: http://"+bindAddr+"/path\r\n" + "Connection: close\r\n\r\n"; p = new Path("webhdfs://"+bindAddr+"/path"); fs = p.getFileSystem(new Configuration()); executor = Executors.newSingleThreadExecutor(); }
int start(final RunNiFiRegistry runner) throws IOException { serverSocket = new ServerSocket(); serverSocket.bind(new InetSocketAddress("localhost", 0)); final int localPort = serverSocket.getLocalPort(); listener = new Listener(serverSocket, runner); final Thread listenThread = new Thread(listener); listenThread.setName("Listen to NiFi Registry"); listenThread.setDaemon(true); listenThread.start(); return localPort; }
private void waitForTask() throws Exception { if (!DirectByteBufferPool.initInstance(config.getByteBufferSize(), Config.getMaxTakePollIter())) { // this is really wrong ... It cannot be already initialized throw new FDTProcolException("The buffer pool cannot be already initialized"); } ExecutorService executor = null; ServerSocketChannel ssc = null; ServerSocket ss = null; Selector sel = null; try { executor = Utils.getStandardExecService("[ Acceptable ServersThreadPool ] ", 2, 10, new ArrayBlockingQueue<Runnable>(65500), Thread.NORM_PRIORITY - 2); ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); ss = ssc.socket(); ss.bind(new InetSocketAddress(config.getPort())); sel = Selector.open(); ssc.register(sel, SelectionKey.OP_ACCEPT); System.out.println("READY"); Utils.waitAndWork(executor, ss, sel, config); } finally { logger.log(Level.INFO, "[FDT] [ waitForTask ] main loop FINISHED!"); // close all the stuff Utils.closeIgnoringExceptions(ssc); Utils.closeIgnoringExceptions(sel); Utils.closeIgnoringExceptions(ss); if (executor != null) { executor.shutdown(); } } }
public static void main(String[] args) throws Exception { try (ServerSocket ss = new ServerSocket(0)) { final int port = ss.getLocalPort(); final Phaser phaser = new Phaser(THREADS + 1); for (int i=0; i<100; i++) { final Socket s = new Socket("localhost", port); s.setSoLinger(false, 0); try (Socket sa = ss.accept()) { sa.setSoLinger(false, 0); final InputStream is = s.getInputStream(); Thread[] threads = new Thread[THREADS]; for (int j=0; j<THREADS; j++) { threads[j] = new Thread() { public void run() { try { phaser.arriveAndAwaitAdvance(); while (is.read() != -1) Thread.sleep(50); } catch (Exception x) { if (!(x instanceof SocketException && x.getMessage().equalsIgnoreCase("socket closed"))) x.printStackTrace(); // ok, expect Socket closed } }}; } for (int j=0; j<100; j++) threads[j].start(); phaser.arriveAndAwaitAdvance(); s.close(); for (int j=0; j<100; j++) threads[j].join(); } } } }
public final void openServerSocket(InetAddress address, int tcpPort) throws IOException { ServerSocketChannel selectable = ServerSocketChannel.open(); selectable.configureBlocking(false); ServerSocket ss = selectable.socket(); if (address == null) ss.bind(new InetSocketAddress(tcpPort)); else ss.bind(new InetSocketAddress(address, tcpPort)); selectable.register(_selector, SelectionKey.OP_ACCEPT); }
/** * {@inheritDoc} */ @Override protected ServerSocketChannel open(SocketAddress localAddress) throws Exception { // Creates the listening ServerSocket ServerSocketChannel channel = ServerSocketChannel.open(); boolean success = false; try { // This is a non blocking socket channel channel.configureBlocking(false); // Configure the server socket, ServerSocket socket = channel.socket(); // Set the reuseAddress flag accordingly with the setting socket.setReuseAddress(isReuseAddress()); // and bind. socket.bind(localAddress, getBacklog()); // Register the channel within the selector for ACCEPT event channel.register(selector, SelectionKey.OP_ACCEPT); success = true; } finally { if (!success) { close(channel); } } return channel; }
/** * Return a free port number. There is no guarantee it will remain free, so * it should be used immediately. * * @returns A free port for binding a local socket */ public static int getFreeSocketPort() { int port = 0; try { ServerSocket s = new ServerSocket(0); port = s.getLocalPort(); s.close(); return port; } catch (IOException e) { // Could not get a free port. Return default port 0. } return port; }
public static void main(String[] args) throws Exception { int readTimeout = 20; ServerSocket ss = new ServerSocket(0); URL url1 = new URL("http://localhost:" + ss.getLocalPort()); HttpClient c1 = HttpClient.New(url1); Method available = HttpClient.class. getDeclaredMethod("available", null); available.setAccessible(true); c1.setReadTimeout(readTimeout); boolean a = (boolean) available.invoke(c1); if (!a) { throw new RuntimeException("connection should be available"); } if (c1.getReadTimeout() != readTimeout) { throw new RuntimeException("read timeout has been altered"); } c1.closeServer(); a = (boolean) available.invoke(c1); if (a) { throw new RuntimeException("connection shouldn't be available"); } ss.close(); }
@Override public ServerSocket createServerSocket (int port, int backlog, InetAddress ifAddress) throws IOException { return new SSLServerSocketImpl (port, backlog, ifAddress, context); }
private int findFreePort() { int port = 8050; try { ServerSocket servSock = new ServerSocket(0); port = servSock.getLocalPort(); servSock.close(); } catch (IOException e) { e.printStackTrace(); } return port; }
/** * Creates a ServerSocket if there isn't any service running. * @return opened ServerSocket * @throws IOException IO Exception if something weird is happening */ private ServerSocket startServerSocket(final int port) throws IOException { if(!this.serverSocketStarted){ log.log(Level.WARNING, "Trying to start a ServerSocket on port: " + port); final ServerSocket socket = new ServerSocket(port); socket.setReuseAddress(true); this.serverSocketStarted = true; this.serverSocketKeepAlive = true; return socket; }else{ log.log(Level.WARNING,"There is currently a ServerSocket running on port: " + port); return null; } }
Server(int port) throws IOException { ss = new ServerSocket(port); sockets = Collections.synchronizedList(new LinkedList<>()); removals = Collections.synchronizedList(new LinkedList<>()); additions = Collections.synchronizedList(new LinkedList<>()); setName("Test-Server"); setDaemon(true); }
/** * Starts the DataServerThread thread * <br>Created server socket opens on given port */ public void start(){ if(!m_MJPEGServerState.equals(MJPEGServerState.PREINIT)){ // This should never happen System.out.println("Error: in DataServerThread.start(), " + "socket is already initialized"); } if(m_running){ // This should never happen System.out.println("Error: in DataServerThread.start(), " + "thread is already running"); } try { m_server = new ServerSocket(m_port); m_server.setReuseAddress(true); System.out.println("Vision stream server started"); } catch (IOException e) { e.printStackTrace(); } this.SetState(MJPEGServerState.CONNECTING); m_running = true; System.out.println("Starting Thread: MJPEGServerThread on port "+m_port); (new Thread(this, "MJPEGServerThread")).start(); }
/** * Configures the given SSL server socket with the requested cipher suites, * protocol versions, and need for client authentication */ private void initServerSocket(ServerSocket ssocket) { SSLServerSocket socket = (SSLServerSocket) ssocket; socket.setEnabledCipherSuites(enabledCiphers); socket.setEnabledProtocols(enabledProtocols); // we don't know if client auth is needed - // after parsing the request we may re-handshake configureClientAuth(socket); configureUseServerCipherSuitesOrder(socket); }
public synchronized static Exporter<RegistryService> exportIfAbsent(int port) { try { new ServerSocket(port).close(); return export(port); } catch (IOException e) { return null; } }
public StreamOverHttp(final Uri uri, final String forceMimeType) throws IOException{ mUri = uri; mName = Utils.getName(mUri); fileMimeType = forceMimeType!=null ? forceMimeType : "*/*"; serverSocket = new ServerSocket(0); mainThread = new Thread(new Runnable(){ public void run(){ try{ while(true) { Socket accept = serverSocket.accept(); new HttpSession(accept,fileMimeType); } }catch(IOException e){ if (debug) Log.w(TAG, e); } } }); mainThread.setName("Stream over HTTP"); mainThread.setDaemon(true); mainThread.start(); }
protected void tryToClose(@Nullable ServerSocket ss) { try { if (ss != null) ss.close(); } catch (IOException e) { if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e); } finally { callback.transportDisabled(); } }
private static int getRandomUnallocatedPort() { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } catch (IOException e) { throw Throwables.propagate(e); } }
public ServerSocket createSocket(int port, int backlog, InetAddress ifAddress, boolean reuseAddr) throws IOException { SSLServerSocket socket = null; socket = new SSLServerSocket(port, backlog, ifAddress, null, reuseAddr); initializeSocket(socket); return socket; }
@Before public void setup() throws IOException { vertx = Vertx.vertx(); try (ServerSocket s = new ServerSocket(0)) { httpPort = s.getLocalPort(); } }