Search in sources :

Example 16 with BindException

use of java.net.BindException in project screenbird by adamhub.

the class ServerIPC method initServerOrClient.

/**
     * Attempts to start a ServerSocket to a well-known-socket. If no 
     * BindException is thrown then ServerSocket creation was successful
     * and this instance is currently the first and only instance running. 
     * <br/><br/>
     * If the BindException is thrown, that means there is another previously
     * opened/running instance of Pastevid/ScreenRecorder running. Once
     * it is determined that this instance is not the first instance, the 
     * attempt to connect to the instance which is running the ServerSocket
     * is made. 
     * 
     * @return <b>True</b> if this Pastevid/Screenrecorder application is the 
     * first instance to be opened. <b>False</b> if it is determined that this
     * instance is not the first opened instance. 
     */
public final synchronized boolean initServerOrClient() {
    try {
        // Open Socket
        this.serverSocket = new ServerSocket(SOCKET_PORT);
        // Update signals
        this.setRunningStatus(true);
        this.ipc.setIsServerOrClient(true);
        log("Base Server is up and running");
        log("Found Server, resuming application");
        return true;
    } catch (BindException e) {
        log("Base Server is already Running");
        log("Found Client, Closing GUI");
        // Update signals
        this.setRunningStatus(false);
        // This is the second instance
        // Calling original server to view
        ClientIPC client = new ClientIPC();
        client.connect();
        client.close();
        // Set this thread to kill
        this.ipc.setIsServerOrClient(false);
    } catch (IOException e) {
        log(e);
    }
    // Kill process
    return false;
}
Also used : BindException(java.net.BindException) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException)

Example 17 with BindException

use of java.net.BindException in project screenbird by adamhub.

the class Server method init.

public void init() {
    try {
        //Open Socket
        this.serverSocket = new ServerSocket(SOCKET_PORT);
        //Update signals
        this.isRunning = true;
        System.out.println("Base Server is up and running");
        //Start server
        //this.serverManager.main();
        this.ipcProtocol.setServer(this);
    } catch (BindException e) {
        System.out.println("Base Server is already Running");
        //Kill process
        System.exit(0);
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}
Also used : BindException(java.net.BindException) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException)

Example 18 with BindException

use of java.net.BindException in project netty by netty.

the class DatagramUnicastTest method testSimpleSend0.

@SuppressWarnings("deprecation")
private void testSimpleSend0(Bootstrap sb, Bootstrap cb, ByteBuf buf, boolean bindClient, final byte[] bytes, int count) throws Throwable {
    final CountDownLatch latch = new CountDownLatch(count);
    sb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() {

                @Override
                public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
                    ByteBuf buf = msg.content();
                    assertEquals(bytes.length, buf.readableBytes());
                    for (byte b : bytes) {
                        assertEquals(b, buf.readByte());
                    }
                    latch.countDown();
                }
            });
        }
    });
    cb.handler(new SimpleChannelInboundHandler<Object>() {

        @Override
        public void channelRead0(ChannelHandlerContext ctx, Object msgs) throws Exception {
        // Nothing will be sent.
        }
    });
    Channel sc = null;
    BindException bindFailureCause = null;
    for (int i = 0; i < 3; i++) {
        try {
            sc = sb.bind().sync().channel();
            break;
        } catch (Exception e) {
            if (e instanceof BindException) {
                logger.warn("Failed to bind to a free port; trying again", e);
                bindFailureCause = (BindException) e;
                refreshLocalAddress(sb);
            } else {
                throw e;
            }
        }
    }
    if (sc == null) {
        throw bindFailureCause;
    }
    Channel cc;
    if (bindClient) {
        cc = cb.bind().sync().channel();
    } else {
        cb.option(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, true);
        cc = cb.register().sync().channel();
    }
    for (int i = 0; i < count; i++) {
        cc.write(new DatagramPacket(buf.retain().duplicate(), addr));
    }
    // release as we used buf.retain() before
    buf.release();
    cc.flush();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    sc.close().sync();
    cc.close().sync();
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) Channel(io.netty.channel.Channel) BindException(java.net.BindException) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf) BindException(java.net.BindException) DatagramPacket(io.netty.channel.socket.DatagramPacket)

Example 19 with BindException

use of java.net.BindException in project neo4j by neo4j.

the class NettyServer method start.

@Override
public void start() throws Throwable {
    // The boss thread accepts new incoming connections and chooses a worker thread to be responsible for the
    // IO of the new connection. We expect new connections to be (comparatively) rare, so we allocate a single
    // thread for this.
    // TODO: In fact, dedicating a whole thread to sit and spin in #select for new connections may be a waste of
    // time, we could have the same event loop groups for both handling new connections and for handling events
    // on existing connections
    bossGroup = new NioEventLoopGroup(1, tf);
    // These threads handle live channels. Each thread has a set of channels it is responsible for, and it will
    // continuously run a #select() loop to react to new events on these channels.
    selectorGroup = new NioEventLoopGroup(NUM_SELECTOR_THREADS, tf);
    for (ProtocolInitializer initializer : bootstrappers) {
        try {
            new ServerBootstrap().option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).group(bossGroup, selectorGroup).channel(NioServerSocketChannel.class).childHandler(initializer.channelInitializer()).bind(initializer.address().socketAddress()).sync();
        } catch (Throwable e) {
            // In any case, we do all this just in order to throw a more helpful bind exception, oh, and here's that part coming right now!
            if (e instanceof BindException) {
                throw new PortBindException(initializer.address(), (BindException) e);
            }
            throw e;
        }
    }
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) PortBindException(org.neo4j.helpers.PortBindException) BindException(java.net.BindException) PortBindException(org.neo4j.helpers.PortBindException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 20 with BindException

use of java.net.BindException in project hadoop by apache.

the class TestNameNodeMXBean method testNNDirectorySize.

@Test(timeout = 120000)
public void testNNDirectorySize() throws Exception {
    Configuration conf = new Configuration();
    conf.setInt(DFSConfigKeys.DFS_HA_TAILEDITS_PERIOD_KEY, 1);
    MiniDFSCluster cluster = null;
    for (int i = 0; i < 5; i++) {
        try {
            // Have to specify IPC ports so the NNs can talk to each other.
            int[] ports = ServerSocketUtil.getPorts(2);
            MiniDFSNNTopology topology = new MiniDFSNNTopology().addNameservice(new MiniDFSNNTopology.NSConf("ns1").addNN(new MiniDFSNNTopology.NNConf("nn1").setIpcPort(ports[0])).addNN(new MiniDFSNNTopology.NNConf("nn2").setIpcPort(ports[1])));
            cluster = new MiniDFSCluster.Builder(conf).nnTopology(topology).numDataNodes(0).build();
            break;
        } catch (BindException e) {
            // retry if race on ports given by ServerSocketUtil#getPorts
            continue;
        }
    }
    if (cluster == null) {
        fail("failed to start mini cluster.");
    }
    FileSystem fs = null;
    try {
        cluster.waitActive();
        FSNamesystem nn0 = cluster.getNamesystem(0);
        FSNamesystem nn1 = cluster.getNamesystem(1);
        checkNNDirSize(cluster.getNameDirs(0), nn0.getNameDirSize());
        checkNNDirSize(cluster.getNameDirs(1), nn1.getNameDirSize());
        cluster.transitionToActive(0);
        fs = cluster.getFileSystem(0);
        DFSTestUtil.createFile(fs, new Path("/file"), 0, (short) 1, 0L);
        //rollEditLog
        HATestUtil.waitForStandbyToCatchUp(cluster.getNameNode(0), cluster.getNameNode(1));
        checkNNDirSize(cluster.getNameDirs(0), nn0.getNameDirSize());
        checkNNDirSize(cluster.getNameDirs(1), nn1.getNameDirSize());
        //Test metric after call saveNamespace
        DFSTestUtil.createFile(fs, new Path("/file"), 0, (short) 1, 0L);
        nn0.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
        nn0.saveNamespace(0, 0);
        checkNNDirSize(cluster.getNameDirs(0), nn0.getNameDirSize());
    } finally {
        cluster.shutdown();
    }
}
Also used : Path(org.apache.hadoop.fs.Path) MiniDFSCluster(org.apache.hadoop.hdfs.MiniDFSCluster) Configuration(org.apache.hadoop.conf.Configuration) HdfsConfiguration(org.apache.hadoop.hdfs.HdfsConfiguration) BindException(java.net.BindException) FileSystem(org.apache.hadoop.fs.FileSystem) DistributedFileSystem(org.apache.hadoop.hdfs.DistributedFileSystem) MiniDFSNNTopology(org.apache.hadoop.hdfs.MiniDFSNNTopology) Test(org.junit.Test)

Aggregations

BindException (java.net.BindException)103 IOException (java.io.IOException)34 InetSocketAddress (java.net.InetSocketAddress)25 ServerSocket (java.net.ServerSocket)22 Test (org.junit.Test)22 File (java.io.File)12 SocketException (java.net.SocketException)10 Configuration (org.apache.hadoop.conf.Configuration)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 InterruptedIOException (java.io.InterruptedIOException)5 MiniDFSNNTopology (org.apache.hadoop.hdfs.MiniDFSNNTopology)5 InetAddress (java.net.InetAddress)4 UnknownHostException (java.net.UnknownHostException)4 RemoteException (java.rmi.RemoteException)4 NIOServerCnxnFactory (org.apache.zookeeper.server.NIOServerCnxnFactory)4 ZooKeeperServer (org.apache.zookeeper.server.ZooKeeperServer)4 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)3 Socket (java.net.Socket)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3