Java Code Examples for java.net.ServerSocket

The following are top voted examples for showing how to use java.net.ServerSocket. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: heapunit   File: DumpSocketsExample.java   Source Code and License 7 votes vote down vote up
@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"));
	}
}
 
Example 2
Project: nn_nex_logging_and_research   File: TCPServer.java   Source Code and License 7 votes vote down vote up
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.");
    }
}
 
Example 3
Project: PNet   File: TLSServer.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
                }
            }
    ));
}
 
Example 4
Project: monarch   File: SocketUtilsJUnitTest.java   Source Code and License 6 votes vote down vote up
@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
        + ")!");
  }
}
 
Example 5
Project: JAddOn   File: Server.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Project: introduction-to-vert.x   File: MyFirstVerticleTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 7
Project: monarch   File: MX4JServerSocketFactory.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 8
Project: JavaLibraries   File: ServerRunner.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 9
Project: PleaseWakeUp   File: SimpleHttpServer.java   Source Code and License 6 votes vote down vote up
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();
        }
    }
}
 
Example 10
Project: pooled-jms   File: SocketProxy.java   Source Code and License 5 votes vote down vote up
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();
    }
}
 
Example 11
Project: apache-tomcat-7.0.73-with-comment   File: NioReceiver.java   Source Code and License 5 votes vote down vote up
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());
    }
}
 
Example 12
Project: q-mail   File: MockImapServer.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 13
Project: CustomWorldGen   File: RConThreadBase.java   Source Code and License 5 votes vote down vote up
/**
 * 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");
    }
}
 
Example 14
Project: openjdk-jdk10   File: Streams.java   Source Code and License 5 votes vote down vote up
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");
    }
 
Example 15
Project: CGL   File: ServerThread.java   Source Code and License 5 votes vote down vote up
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();
		}
	}
}
 
Example 16
Project: can4eve   File: Can4eve.java   Source Code and License 5 votes vote down vote up
/**
 * 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();
}
 
Example 17
Project: ditb   File: SslSocketConnectorSecure.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 18
Project: react-native-sockets   File: SocketServer.java   Source Code and License 5 votes vote down vote up
@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);
    }
}
 
Example 19
Project: hadoop   File: TestWebHdfsContentLength.java   Source Code and License 5 votes vote down vote up
@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();    
}
 
Example 20
Project: nifi-registry   File: NiFiRegistryListener.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 21
Project: fdt   File: FDT.java   Source Code and License 5 votes vote down vote up
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();
        }
    }
}
 
Example 22
Project: openjdk-jdk10   File: Race.java   Source Code and License 5 votes vote down vote up
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();
            }
        }
    }
}
 
Example 23
Project: L2jBrasil   File: SelectorThread.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 24
Project: neoscada   File: NioSocketAcceptor.java   Source Code and License 5 votes vote down vote up
/**
 * {@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;
}
 
Example 25
Project: hadoop-oss   File: NetUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 26
Project: jdk8u-jdk   File: IsAvailable.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 27
Project: OpenJSharp   File: SSLServerSocketFactoryImpl.java   Source Code and License 5 votes vote down vote up
@Override
public ServerSocket
createServerSocket (int port, int backlog, InetAddress ifAddress)
throws IOException
{
    return new SSLServerSocketImpl (port, backlog, ifAddress, context);
}
 
Example 28
Project: greycat   File: DeleteTest.java   Source Code and License 5 votes vote down vote up
private int findFreePort() {
    int port = 8050;
    try {
        ServerSocket servSock = new ServerSocket(0);
        port = servSock.getLocalPort();
        servSock.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return port;
}
 
Example 29
Project: Byter   File: NetworkManager.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 30
Project: openjdk-jdk10   File: Server.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 31
Project: FRC-2017-Public   File: MJPEGServerSocket.java   Source Code and License 5 votes vote down vote up
/**
 * 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();
}
 
Example 32
Project: tomcat7   File: JSSESocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 33
Project: EatDubbo   File: SimpleRegistryExporter.java   Source Code and License 5 votes vote down vote up
public synchronized static Exporter<RegistryService> exportIfAbsent(int port) {
    try {
        new ServerSocket(port).close();
        return export(port);
    } catch (IOException e) {
        return null;
    }
}
 
Example 34
Project: aos-FileCoreLibrary   File: StreamOverHttp.java   Source Code and License 5 votes vote down vote up
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();


  }
 
Example 35
Project: apache-tomcat-7.0.73-with-comment   File: JSSESocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
}
 
Example 36
Project: Nird2   File: TcpPlugin.java   Source Code and License 5 votes vote down vote up
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();
	}
}
 
Example 37
Project: dubbo2   File: SimpleRegistryExporter.java   Source Code and License 5 votes vote down vote up
public synchronized static Exporter<RegistryService> exportIfAbsent(int port) {
    try {
        new ServerSocket(port).close();
        return export(port);
    } catch (IOException e) {
        return null;
    }
}
 
Example 38
Project: verify-hub   File: EidasSessionResourceContractTest.java   Source Code and License 5 votes vote down vote up
private static int getRandomUnallocatedPort() {
    try (ServerSocket socket = new ServerSocket(0)) {
        return socket.getLocalPort();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
 
Example 39
Project: tomcatjss   File: JSSSocketFactory.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 40
Project: vertx-graphql-utils   File: GraphQLBodyCodecTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setup() throws IOException {
	vertx = Vertx.vertx();
	try (ServerSocket s = new ServerSocket(0)) {
		httpPort = s.getLocalPort();
	}
}