javax.net.ServerSocketFactory Java Examples

The following examples show how to use javax.net.ServerSocketFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LdapServer.java    From learnjavabug with MIT License 6 votes vote down vote up
public static void run(String ... args) {
  int port = args.length > 0 ? Integer.parseInt(args[0]) : 43658;
  //TODO 把resources下的Calc.class 或者 自定义修改编译后target目录下的Calc.class 拷贝到下面代码所示http://host:port的web服务器根目录即可
  String url = args.length > 0 ? args[1] : "http://localhost/#Calc";
  try {
    InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(LDAP_BASE);
    config.setListenerConfigs(new InMemoryListenerConfig(
        "listen", //$NON-NLS-1$
        InetAddress.getByName("0.0.0.0"), //$NON-NLS-1$
        port,
        ServerSocketFactory.getDefault(),
        SocketFactory.getDefault(),
        (SSLSocketFactory) SSLSocketFactory.getDefault()));

    config.addInMemoryOperationInterceptor(new OperationInterceptor(new URL(url)));
    InMemoryDirectoryServer ds = new InMemoryDirectoryServer(config);
    System.out.println("Listening on 0.0.0.0:" + port); //$NON-NLS-1$
    ds.startListening();

  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example #2
Source File: DefaultSSLServSocketFac.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSSFacProvider =
        Security.getProperty("ssl.ServerSocketFactory.provider");

    try {
        Security.setProperty("ssl.ServerSocketFactory.provider", "oops");
        ServerSocketFactory ssocketFactory =
                    SSLServerSocketFactory.getDefault();
        SSLServerSocket sslServerSocket =
                    (SSLServerSocket)ssocketFactory.createServerSocket();
    } catch (Exception e) {
        if (!(e.getCause() instanceof ClassNotFoundException)) {
            throw e;
        }
        // get the expected exception
    } finally {
        // restore the security properties
        if (reservedSSFacProvider == null) {
            reservedSSFacProvider = "";
        }
        Security.setProperty("ssl.ServerSocketFactory.provider",
                                                reservedSSFacProvider);
    }
}
 
Example #3
Source File: B8025710.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
HttpServer() throws Exception {
    super("HttpServer Thread");

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(keystorefile), passphrase.toCharArray());
    KeyManagerFactory factory = KeyManagerFactory.getInstance("SunX509");
    factory.init(ks, passphrase.toCharArray());
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(factory.getKeyManagers(), null, null);

    sslSocketFactory = ctx.getSocketFactory();

    // Create the server that the test wants to connect to via the proxy
    serverSocket = ServerSocketFactory.getDefault().createServerSocket();
    serverSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
}
 
Example #4
Source File: ServerTSap.java    From iec61850bean with Apache License 2.0 6 votes vote down vote up
/**
 * Use this constructor to create a server TSAP that can listen on a port, with a specified
 * ServerSocketFactory.
 *
 * @param port the TCP port that the ServerSocket will connect to. Should be between 1 and 65535.
 * @param connectionListener the ConnectionListener that will be notified when remote TSAPs are
 *     connecting or the server stopped listening.
 * @param backlog is passed to the java.net.ServerSocket
 * @param bindAddr the IP address to bind to. It is passed to java.net.ServerSocket
 * @param serverSocketFactory The ServerSocketFactory to be used to create the ServerSocket
 */
public ServerTSap(
    int port,
    int backlog,
    InetAddress bindAddr,
    TConnectionListener connectionListener,
    ServerSocketFactory serverSocketFactory) {
  if (port < 1 || port > 65535) {
    throw new IllegalArgumentException("port number is out of bound");
  }

  this.port = port;
  this.backlog = backlog;
  this.bindAddr = bindAddr;
  this.connectionListener = connectionListener;
  this.serverSocketFactory = serverSocketFactory;
}
 
Example #5
Source File: B8025710.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
HttpServer() throws Exception {
    super("HttpServer Thread");

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(keystorefile), passphrase.toCharArray());
    KeyManagerFactory factory = KeyManagerFactory.getInstance("SunX509");
    factory.init(ks, passphrase.toCharArray());
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(factory.getKeyManagers(), null, null);

    sslSocketFactory = ctx.getSocketFactory();

    // Create the server that the test wants to connect to via the proxy
    serverSocket = ServerSocketFactory.getDefault().createServerSocket();
    serverSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
}
 
Example #6
Source File: DefaultSSLServSocketFac.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSSFacProvider =
        Security.getProperty("ssl.ServerSocketFactory.provider");

    try {
        Security.setProperty("ssl.ServerSocketFactory.provider", "oops");
        ServerSocketFactory ssocketFactory =
                    SSLServerSocketFactory.getDefault();
        SSLServerSocket sslServerSocket =
                    (SSLServerSocket)ssocketFactory.createServerSocket();
    } catch (Exception e) {
        if (!(e.getCause() instanceof ClassNotFoundException)) {
            throw e;
        }
        // get the expected exception
    } finally {
        // restore the security properties
        if (reservedSSFacProvider == null) {
            reservedSSFacProvider = "";
        }
        Security.setProperty("ssl.ServerSocketFactory.provider",
                                                reservedSSFacProvider);
    }
}
 
Example #7
Source File: SslServerSocketFactory.java    From game-server with MIT License 6 votes vote down vote up
public static ServerSocketFactory getServerSocketFactory()
        throws IOException {
    if (isSslEnabled()) {
        if (sslFactory == null) {
            try {
                sslFactory = GateSslContextFactory.getInstance(true)
                        .getServerSocketFactory();
            } catch (Exception e) {
                IOException ioe = new IOException(
                        "could not create SSL socket");
                ioe.initCause(e);
                throw ioe;
            }
        }
        return sslFactory;
    } else {
        if (factory == null) {
            factory = new SslServerSocketFactory();
        }
        return factory;
    }

}
 
Example #8
Source File: TimeoutTest.java    From jcifs-ng with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test ( expected = ConnectionTimeoutException.class )
public void testConnectTimeoutRead () throws IOException {
    Set<Thread> threadsBefore = new HashSet<>(Thread.getAllStackTraces().keySet());
    try ( ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(0, -1, InetAddress.getLoopbackAddress()) ) {
        int port = ss.getLocalPort();
        InetAddress addr = ss.getInetAddress();

        long start = System.currentTimeMillis();
        CIFSContext ctx = lowConnectTimeout(getContext());
        try ( SmbResource f = new SmbFile(
            new URL("smb", addr.getHostAddress(), port, "/" + getTestShare() + "/connect.test", ctx.getUrlHandler()),
            ctx) ) {
            runConnectTimeoutTest(threadsBefore, start, ctx, f);
        }
    }
}
 
Example #9
Source File: BaseMainService.java    From android-http-server with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    isServiceStarted = true;

    if (activity == null) {
        throw new NullPointerException("Activity must be set at this point.");
    }
    ServerConfigFactory serverConfigFactory = getServerConfigFactory(activity);

    doFirstRunChecks(serverConfigFactory);

    controller = new ControllerImpl(serverConfigFactory, ServerSocketFactory.getDefault(), this);
    controller.start();

    return START_STICKY;
}
 
Example #10
Source File: DefaultSSLServSocketFac.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSSFacProvider =
        Security.getProperty("ssl.ServerSocketFactory.provider");

    try {
        Security.setProperty("ssl.ServerSocketFactory.provider", "oops");
        ServerSocketFactory ssocketFactory =
                    SSLServerSocketFactory.getDefault();
        SSLServerSocket sslServerSocket =
                    (SSLServerSocket)ssocketFactory.createServerSocket();
    } catch (Exception e) {
        if (!(e.getCause() instanceof ClassNotFoundException)) {
            throw e;
        }
        // get the expected exception
    } finally {
        // restore the security properties
        if (reservedSSFacProvider == null) {
            reservedSSFacProvider = "";
        }
        Security.setProperty("ssl.ServerSocketFactory.provider",
                                                reservedSSFacProvider);
    }
}
 
Example #11
Source File: DefaultSSLServSocketFac.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSSFacProvider =
        Security.getProperty("ssl.ServerSocketFactory.provider");

    try {
        Security.setProperty("ssl.ServerSocketFactory.provider", "oops");
        ServerSocketFactory ssocketFactory =
                    SSLServerSocketFactory.getDefault();
        SSLServerSocket sslServerSocket =
                    (SSLServerSocket)ssocketFactory.createServerSocket();
    } catch (Exception e) {
        if (!(e.getCause() instanceof ClassNotFoundException)) {
            throw e;
        }
        // get the expected exception
    } finally {
        // restore the security properties
        if (reservedSSFacProvider == null) {
            reservedSSFacProvider = "";
        }
        Security.setProperty("ssl.ServerSocketFactory.provider",
                                                reservedSSFacProvider);
    }
}
 
Example #12
Source File: ProxyServer.java    From AndServer with Apache License 2.0 6 votes vote down vote up
public HttpServer(InetAddress inetAddress, int port, int timeout, ServerSocketFactory socketFactory,
    SSLSocketInitializer sslSocketInitializer, HttpRequestHandler handler) {
    this.mInetAddress = inetAddress;
    this.mPort = port;
    this.mTimeout = timeout;
    this.mSocketFactory = socketFactory;
    this.mSSLSocketInitializer = sslSocketInitializer;
    this.mHandler = handler;

    HttpProcessor inProcessor = new ImmutableHttpProcessor(
        new ResponseDate(),
        new ResponseServer(AndServer.INFO),
        new ResponseContent(),
        new ResponseConnControl());

    UriHttpRequestHandlerMapper mapper = new UriHttpRequestHandlerMapper();
    mapper.register("*", mHandler);

    this.mHttpService = new HttpService(inProcessor, mapper);
}
 
Example #13
Source File: B8025710.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
HttpServer() throws Exception {
    super("HttpServer Thread");

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(keystorefile), passphrase.toCharArray());
    KeyManagerFactory factory = KeyManagerFactory.getInstance("SunX509");
    factory.init(ks, passphrase.toCharArray());
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(factory.getKeyManagers(), null, null);

    sslSocketFactory = ctx.getSocketFactory();

    // Create the server that the test wants to connect to via the proxy
    serverSocket = ServerSocketFactory.getDefault().createServerSocket();
    serverSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
}
 
Example #14
Source File: B8025710.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
HttpServer() throws Exception {
    super("HttpServer Thread");

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(keystorefile), passphrase.toCharArray());
    KeyManagerFactory factory = KeyManagerFactory.getInstance("SunX509");
    factory.init(ks, passphrase.toCharArray());
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(factory.getKeyManagers(), null, null);

    sslSocketFactory = ctx.getSocketFactory();

    // Create the server that the test wants to connect to via the proxy
    serverSocket = ServerSocketFactory.getDefault().createServerSocket();
    serverSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
}
 
Example #15
Source File: LdapServer.java    From rogue-jndi with MIT License 6 votes vote down vote up
public static void start() {
    try {
        System.out.println("Starting LDAP server on 0.0.0.0:" + Config.ldapPort);
        InMemoryDirectoryServerConfig serverConfig = new InMemoryDirectoryServerConfig("dc=example,dc=com");
        serverConfig.setListenerConfigs(new InMemoryListenerConfig(
                "listen",
                InetAddress.getByName("0.0.0.0"),
                Config.ldapPort,
                ServerSocketFactory.getDefault(),
                SocketFactory.getDefault(),
                (SSLSocketFactory) SSLSocketFactory.getDefault()));

        serverConfig.addInMemoryOperationInterceptor(new LdapServer());
        InMemoryDirectoryServer ds = new InMemoryDirectoryServer(serverConfig);
        ds.startListening();
    }
    catch ( Exception e ) {
        e.printStackTrace();
    }
}
 
Example #16
Source File: TcpSinkTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
public TestTCPServer() {
	ServerSocket serverSocket = null;
	ExecutorService executor = null;
	try {
		serverSocket = ServerSocketFactory.getDefault().createServerSocket(0);
		System.setProperty("tcp.sink.test.port", Integer.toString(serverSocket.getLocalPort()));
		executor = Executors.newSingleThreadExecutor();
	}
	catch (IOException e) {
		e.printStackTrace();
	}
	this.serverSocket = serverSocket;
	this.executor = executor;
	this.decoder = new ByteArrayCrLfSerializer();
	executor.execute(this);
}
 
Example #17
Source File: DefaultSSLServSocketFac.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSSFacProvider =
        Security.getProperty("ssl.ServerSocketFactory.provider");

    try {
        Security.setProperty("ssl.ServerSocketFactory.provider", "oops");
        ServerSocketFactory ssocketFactory =
                    SSLServerSocketFactory.getDefault();
        SSLServerSocket sslServerSocket =
                    (SSLServerSocket)ssocketFactory.createServerSocket();
    } catch (Exception e) {
        if (!(e.getCause() instanceof ClassNotFoundException)) {
            throw e;
        }
        // get the expected exception
    } finally {
        // restore the security properties
        if (reservedSSFacProvider == null) {
            reservedSSFacProvider = "";
        }
        Security.setProperty("ssl.ServerSocketFactory.provider",
                                                reservedSSFacProvider);
    }
}
 
Example #18
Source File: TimeoutTest.java    From jcifs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test ( expected = ConnectionTimeoutException.class )
public void testConnectTimeoutRead () throws IOException {
    Set<Thread> threadsBefore = new HashSet<>(Thread.getAllStackTraces().keySet());
    try ( ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(0, -1, InetAddress.getLoopbackAddress()) ) {
        int port = ss.getLocalPort();
        InetAddress addr = ss.getInetAddress();

        long start = System.currentTimeMillis();
        CIFSContext ctx = lowConnectTimeout(getContext());
        try ( SmbResource f = new SmbFile(
            new URL("smb", addr.getHostAddress(), port, "/" + getTestShare() + "/connect.test", ctx.getUrlHandler()),
            ctx) ) {
            runConnectTimeoutTest(threadsBefore, start, ctx, f);
        }
    }
}
 
Example #19
Source File: ProxyTunnelServer.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public ProxyTunnelServer() throws IOException {
    if (ss == null) {
        ss = (ServerSocket) ServerSocketFactory.getDefault()
                .createServerSocket(0);
        ss.setSoTimeout(TIMEOUT);
    }
}
 
Example #20
Source File: B8025710.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
ProxyServer() throws Exception {
    super("ProxyServer Thread");

    // Create the http proxy server socket
    proxySocket = ServerSocketFactory.getDefault().createServerSocket();
    proxySocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
}
 
Example #21
Source File: ArtemisPortChecker.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean isPortAvailable( String host, int port )
{
    try
    {
        ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(
            port, 1, InetAddress.getByName( host ) );
        serverSocket.close();
        return true;
    }
    catch ( Exception ex )
    {
        return false;
    }
}
 
Example #22
Source File: B8025710.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
ProxyServer() throws Exception {
    super("ProxyServer Thread");

    // Create the http proxy server socket
    proxySocket = ServerSocketFactory.getDefault().createServerSocket();
    proxySocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
}
 
Example #23
Source File: B8025710.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
ProxyServer() throws Exception {
    super("ProxyServer Thread");

    // Create the http proxy server socket
    proxySocket = ServerSocketFactory.getDefault().createServerSocket();
    proxySocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
}
 
Example #24
Source File: B8025710.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
ProxyServer() throws Exception {
    super("ProxyServer Thread");

    // Create the http proxy server socket
    proxySocket = ServerSocketFactory.getDefault().createServerSocket();
    proxySocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
}
 
Example #25
Source File: ProxyTunnelServer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public ProxyTunnelServer() throws IOException {
    if (ss == null) {
      ss = (ServerSocket) ServerSocketFactory.getDefault().
      createServerSocket(0);
    }
    setDaemon(true);
}
 
Example #26
Source File: SocketUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isPortAvailable(int port) {
	try {
		ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, 1,
			InetAddress.getByName("localhost"));
		serverSocket.close();
		return true;
	}
	catch (Exception ex) {
		return false;
	}
}
 
Example #27
Source File: ReplicationMessageReceive.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Used to create a <code>ServerSocket</code> for listening to connections
 * from the master.
 *
 * @return an instance of the <code>ServerSocket</code> class.
 *
 * @throws PrivilegedActionException if an exception occurs while trying
 *                                   to open a connection.
 */
private ServerSocket createServerSocket() throws PrivilegedActionException {
    //create a ServerSocket at the specified host name and the
    //port number.
    return   AccessController.doPrivileged
        (new PrivilegedExceptionAction<ServerSocket>() {
        public ServerSocket run() throws IOException, StandardException {
            ServerSocketFactory sf = ServerSocketFactory.getDefault();
            return sf.createServerSocket(slaveAddress.getPortNumber(),
                0, slaveAddress.getHostAddress());
        }
    });
}
 
Example #28
Source File: NetUtilTest.java    From vjtools with Apache License 2.0 5 votes vote down vote up
@Test
public void portDetect() throws UnknownHostException, IOException {
	int port = NetUtil.findRandomAvailablePort(20000, 20100);
	assertThat(port).isBetween(20000, 20100);
	System.out.println("random port:" + port);

	assertThat(NetUtil.isPortAvailable(port)).isTrue();

	int port2 = NetUtil.findAvailablePortFrom(port);
	assertThat(port2).isEqualTo(port);

	int port3 = NetUtil.findRandomAvailablePort();

	assertThat(port3).isBetween(NetUtil.PORT_RANGE_MIN, NetUtil.PORT_RANGE_MAX);
	System.out.println("random port:" + port3);

	// 尝试占住一个端口
	ServerSocket serverSocket = null;
	try {
		serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, 1,
				InetAddress.getByName("localhost"));

		assertThat(NetUtil.isPortAvailable(port)).isFalse();

		int port4 = NetUtil.findAvailablePortFrom(port);
		assertThat(port4).isEqualTo(port + 1);

		try {
			int port5 = NetUtil.findRandomAvailablePort(port, port);
			fail("should fail before");
		} catch (Throwable t) {
			assertThat(t).isInstanceOf(IllegalStateException.class);
		}

	} finally {
		IOUtil.close(serverSocket);
	}

}
 
Example #29
Source File: NetUtilTest.java    From vjtools with Apache License 2.0 5 votes vote down vote up
@Test
public void portDetect() throws UnknownHostException, IOException {
	int port = NetUtil.findRandomAvailablePort(20000, 20100);
	assertThat(port).isBetween(20000, 20100);
	System.out.println("random port:" + port);

	assertThat(NetUtil.isPortAvailable(port)).isTrue();

	int port2 = NetUtil.findAvailablePortFrom(port);
	assertThat(port2).isEqualTo(port);

	int port3 = NetUtil.findRandomAvailablePort();

	assertThat(port3).isBetween(NetUtil.PORT_RANGE_MIN, NetUtil.PORT_RANGE_MAX);
	System.out.println("random port:" + port3);

	// 尝试占住一个端口
	ServerSocket serverSocket = null;
	try {
		serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, 1,
				InetAddress.getByName("localhost"));

		assertThat(NetUtil.isPortAvailable(port)).isFalse();

		int port4 = NetUtil.findAvailablePortFrom(port);
		assertThat(port4).isEqualTo(port + 1);

		try {
			int port5 = NetUtil.findRandomAvailablePort(port, port);
			fail("should fail before");
		} catch (Throwable t) {
			assertThat(t).isInstanceOf(IllegalStateException.class);
		}

	} finally {
		IOUtil.close(serverSocket);
	}

}
 
Example #30
Source File: SocketUtilsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void findAvailableTcpPortWhenPortOnLoopbackInterfaceIsNotAvailable() throws Exception {
	int port = SocketUtils.findAvailableTcpPort();
	ServerSocket socket = ServerSocketFactory.getDefault().createServerSocket(port, 1, InetAddress.getByName("localhost"));
	try {
		// will only look for the exact port
		assertThatIllegalStateException().isThrownBy(() ->
				SocketUtils.findAvailableTcpPort(port, port))
			.withMessageStartingWith("Could not find an available TCP port")
			.withMessageEndingWith("after 1 attempts");
	}
	finally {
		socket.close();
	}
}