Search in sources :

Example 1 with ServerSocket

use of java.net.ServerSocket in project camel by apache.

the class MllpTcpServerConsumer method doStart.

@Override
protected void doStart() throws Exception {
    log.debug("doStart() - creating acceptor thread");
    ServerSocket serverSocket = new ServerSocket();
    if (null != endpoint.receiveBufferSize) {
        serverSocket.setReceiveBufferSize(endpoint.receiveBufferSize);
    }
    serverSocket.setReuseAddress(endpoint.reuseAddress);
    // Accept Timeout
    serverSocket.setSoTimeout(endpoint.acceptTimeout);
    InetSocketAddress socketAddress;
    if (null == endpoint.getHostname()) {
        socketAddress = new InetSocketAddress(endpoint.getPort());
    } else {
        socketAddress = new InetSocketAddress(endpoint.getHostname(), endpoint.getPort());
    }
    long startTicks = System.currentTimeMillis();
    do {
        try {
            serverSocket.bind(socketAddress, endpoint.backlog);
        } catch (BindException bindException) {
            if (System.currentTimeMillis() > startTicks + endpoint.getBindTimeout()) {
                log.error("Failed to bind to address {} within timeout {}", socketAddress, endpoint.getBindTimeout());
                throw bindException;
            } else {
                log.warn("Failed to bind to address {} - retrying in {} milliseconds", socketAddress, endpoint.getBindRetryInterval());
                Thread.sleep(endpoint.getBindRetryInterval());
            }
        }
    } while (!serverSocket.isBound());
    serverSocketThread = new ServerSocketThread(serverSocket);
    serverSocketThread.start();
    super.doStart();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) BindException(java.net.BindException) ServerSocket(java.net.ServerSocket)

Example 2 with ServerSocket

use of java.net.ServerSocket in project camel by apache.

the class MllpTcpServerConsumerBindTimeoutTest method testReceiveSingleMessage.

@Test
public void testReceiveSingleMessage() throws Exception {
    result.expectedMessageCount(1);
    Thread tmpThread = new Thread() {

        public void run() {
            try {
                ServerSocket tmpSocket = new ServerSocket(mllpClient.getMllpPort());
                Thread.sleep(15000);
                tmpSocket.close();
            } catch (Exception ex) {
                throw new RuntimeException("Exception caught in dummy listener", ex);
            }
        }
    };
    tmpThread.start();
    context.start();
    mllpClient.connect();
    mllpClient.sendMessageAndWaitForAcknowledgement(generateMessage(), 10000);
    assertMockEndpointsSatisfied(10, TimeUnit.SECONDS);
}
Also used : ServerSocket(java.net.ServerSocket) Test(org.junit.Test)

Example 3 with ServerSocket

use of java.net.ServerSocket in project camel by apache.

the class MllpSocketUtilSocketTest method setUp.

@Before
public void setUp() throws Exception {
    serverSocket = new ServerSocket(0);
    socket = new Socket();
}
Also used : ServerSocket(java.net.ServerSocket) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) Before(org.junit.Before)

Example 4 with ServerSocket

use of java.net.ServerSocket in project flink by apache.

the class ZooKeeperLeaderRetrievalTest method testConnectingAddressRetrievalWithDelayedLeaderElection.

/**
	 * Tests that LeaderRetrievalUtils.findConnectingAdress finds the correct connecting address
	 * in case of an old leader address in ZooKeeper and a subsequent election of a new leader.
	 * The findConnectingAddress should block until the new leader has been elected and his
	 * address has been written to ZooKeeper.
	 */
@Test
public void testConnectingAddressRetrievalWithDelayedLeaderElection() throws Exception {
    FiniteDuration timeout = new FiniteDuration(1, TimeUnit.MINUTES);
    Configuration config = new Configuration();
    long sleepingTime = 1000;
    config.setString(HighAvailabilityOptions.HA_MODE, "zookeeper");
    config.setString(HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM, testingServer.getConnectString());
    LeaderElectionService leaderElectionService = null;
    LeaderElectionService faultyLeaderElectionService;
    ServerSocket serverSocket;
    InetAddress localHost;
    Thread thread;
    CuratorFramework[] client = new CuratorFramework[2];
    try {
        client[0] = ZooKeeperUtils.startCuratorFramework(config);
        client[1] = ZooKeeperUtils.startCuratorFramework(config);
        String wrongHostPort = NetUtils.unresolvedHostAndPortToNormalizedString("1.1.1.1", 1234);
        String wrongAddress = JobManager.getRemoteJobManagerAkkaURL(AkkaUtils.getAkkaProtocol(config), wrongHostPort, Option.<String>empty());
        try {
            localHost = InetAddress.getLocalHost();
            serverSocket = new ServerSocket(0, 50, localHost);
        } catch (UnknownHostException e) {
            // may happen if disconnected. skip test.
            System.err.println("Skipping 'testNetworkInterfaceSelection' test.");
            return;
        } catch (IOException e) {
            // may happen in certain test setups, skip test.
            System.err.println("Skipping 'testNetworkInterfaceSelection' test.");
            return;
        }
        InetSocketAddress correctInetSocketAddress = new InetSocketAddress(localHost, serverSocket.getLocalPort());
        String hostPort = NetUtils.unresolvedHostAndPortToNormalizedString(localHost.getHostName(), correctInetSocketAddress.getPort());
        String correctAddress = JobManager.getRemoteJobManagerAkkaURL(AkkaUtils.getAkkaProtocol(config), hostPort, Option.<String>empty());
        faultyLeaderElectionService = ZooKeeperUtils.createLeaderElectionService(client[0], config);
        TestingContender wrongLeaderAddressContender = new TestingContender(wrongAddress, faultyLeaderElectionService);
        faultyLeaderElectionService.start(wrongLeaderAddressContender);
        FindConnectingAddress findConnectingAddress = new FindConnectingAddress(config, timeout);
        thread = new Thread(findConnectingAddress);
        thread.start();
        leaderElectionService = ZooKeeperUtils.createLeaderElectionService(client[1], config);
        TestingContender correctLeaderAddressContender = new TestingContender(correctAddress, leaderElectionService);
        Thread.sleep(sleepingTime);
        faultyLeaderElectionService.stop();
        leaderElectionService.start(correctLeaderAddressContender);
        thread.join();
        InetAddress result = findConnectingAddress.getInetAddress();
        // check that we can connect to the localHost
        Socket socket = new Socket();
        try {
            // port 0 = let the OS choose the port
            SocketAddress bindP = new InetSocketAddress(result, 0);
            // machine
            socket.bind(bindP);
            socket.connect(correctInetSocketAddress, 1000);
        } finally {
            socket.close();
        }
    } finally {
        if (leaderElectionService != null) {
            leaderElectionService.stop();
        }
        if (client[0] != null) {
            client[0].close();
        }
        if (client[1] != null) {
            client[1].close();
        }
    }
}
Also used : Configuration(org.apache.flink.configuration.Configuration) UnknownHostException(java.net.UnknownHostException) InetSocketAddress(java.net.InetSocketAddress) FiniteDuration(scala.concurrent.duration.FiniteDuration) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) CuratorFramework(org.apache.curator.framework.CuratorFramework) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) InetAddress(java.net.InetAddress) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) Test(org.junit.Test)

Example 5 with ServerSocket

use of java.net.ServerSocket in project flink by apache.

the class IPv6HostnamesITCase method getLocalIPv6Address.

private Inet6Address getLocalIPv6Address() {
    try {
        Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            NetworkInterface netInterface = e.nextElement();
            // for each address of the network interface
            Enumeration<InetAddress> ee = netInterface.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress addr = ee.nextElement();
                if (addr instanceof Inet6Address && (!addr.isLoopbackAddress()) && (!addr.isAnyLocalAddress())) {
                    // see if it is possible to bind to the address
                    InetSocketAddress socketAddress = new InetSocketAddress(addr, 0);
                    try {
                        log.info("Considering address " + addr);
                        // test whether we can bind a socket to that address
                        log.info("Testing whether sockets can bind to " + addr);
                        ServerSocket sock = new ServerSocket();
                        sock.bind(socketAddress);
                        sock.close();
                        // test whether Akka's netty can bind to the address
                        log.info("Testing whether Akka can use " + addr);
                        int port = NetUtils.getAvailablePort();
                        ActorSystem as = AkkaUtils.createActorSystem(new Configuration(), new Some<scala.Tuple2<String, Object>>(new scala.Tuple2<String, Object>(addr.getHostAddress(), port)));
                        as.shutdown();
                        log.info("Using address " + addr);
                        return (Inet6Address) addr;
                    } catch (IOException ignored) {
                    // fall through the loop
                    }
                }
            }
        }
        return null;
    } catch (Exception e) {
        return null;
    }
}
Also used : ActorSystem(akka.actor.ActorSystem) Configuration(org.apache.flink.configuration.Configuration) InetSocketAddress(java.net.InetSocketAddress) NetworkInterface(java.net.NetworkInterface) Inet6Address(java.net.Inet6Address) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) IOException(java.io.IOException) Tuple2(org.apache.flink.api.java.tuple.Tuple2) InetAddress(java.net.InetAddress)

Aggregations

ServerSocket (java.net.ServerSocket)655 IOException (java.io.IOException)306 Socket (java.net.Socket)254 InetSocketAddress (java.net.InetSocketAddress)126 Test (org.junit.Test)94 SocketException (java.net.SocketException)54 InputStream (java.io.InputStream)48 SocketTimeoutException (java.net.SocketTimeoutException)42 OutputStream (java.io.OutputStream)40 InetAddress (java.net.InetAddress)39 BindException (java.net.BindException)27 URL (java.net.URL)26 InputStreamReader (java.io.InputStreamReader)23 File (java.io.File)22 UnknownHostException (java.net.UnknownHostException)22 SSLSocket (javax.net.ssl.SSLSocket)21 BufferedReader (java.io.BufferedReader)20 SSLServerSocket (javax.net.ssl.SSLServerSocket)20 ServerSocketChannel (java.nio.channels.ServerSocketChannel)15 SocketChannel (java.nio.channels.SocketChannel)14