Java Code Examples for io.netty.bootstrap.Bootstrap#handler()

The following examples show how to use io.netty.bootstrap.Bootstrap#handler() . 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: NettyClientConnector.java    From rpc-benchmark with Apache License 2.0 6 votes vote down vote up
private void doConnect(EventLoopGroup loupGroup, Class<? extends SocketChannel> serverChannelClass, boolean isEpoll)
		throws InterruptedException {

	final Bootstrap bootstrap = new Bootstrap();

	if (isEpoll) {
		bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);
	}

	bootstrap.option(ChannelOption.SO_REUSEADDR, true);
	bootstrap.option(ChannelOption.SO_RCVBUF, 256 * 1024);
	bootstrap.option(ChannelOption.SO_SNDBUF, 256 * 1024);
	bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, //
			new WriteBufferWaterMark(1024 * 1024, 2048 * 1024));

	bootstrap.group(loupGroup);
	bootstrap.channel(serverChannelClass);
	bootstrap.handler(new BenchmarkChannelInitializer(futureContainer));

	for (int i = 0; i < CONNECT_COUNT; i++) {
		channels[i] = bootstrap.connect(host, port).sync().channel();
		queues[i] = new MpscAtomicArrayQueue<>(4 * 1024);
	}
}
 
Example 2
Source File: ChannelMediator.java    From flashback with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Establishing TCP connection to server
 *
 * @param remoteAddress remote address
 * */
public ChannelFuture connectToServer(final InetSocketAddress remoteAddress) {
  if (remoteAddress == null) {
    throw new IllegalStateException("remote address is null");
  }
  Bootstrap bootstrap = new Bootstrap().group(_upstreamWorkerGroup);
  bootstrap.channelFactory(NioSocketChannel::new);
  ServerChannelHandler serverChannelHandler = new ServerChannelHandler(this);

  bootstrap.handler(new ChannelInitializer<Channel>() {
    protected void initChannel(Channel ch)
        throws Exception {
      initChannelPipeline(ch.pipeline(), serverChannelHandler, _serverConnectionIdleTimeoutMsec);
      _serverChannel = ch;
    }
  });
  LOG.debug("Server channel is ready. About to connect....");
  return bootstrap.connect(remoteAddress);
}
 
Example 3
Source File: NettyClient.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String host = "localhost";
    int port = 8080;
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new RequestDataEncoder(), new ResponseDataDecoder(), new ClientHandler());
            }
        });

        ChannelFuture f = b.connect(host, port).sync();

        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }
}
 
Example 4
Source File: NettyClientServerCommunicationSystemClientSide.java    From library with Apache License 2.0 6 votes vote down vote up
/**
 * Tulio Ribeiro Connect to specific replica and returns the ChannelFuture.
 * sessionClientToReplica is replaced with the new connection. Removed redundant
 * code.
 */
public synchronized ChannelFuture connectToReplica(int replicaId, SecretKeyFactory fac)
		throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {

	String str = this.clientId + ":" + replicaId;
	PBEKeySpec spec = TOMUtil.generateKeySpec(str.toCharArray());
	SecretKey authKey = fac.generateSecret(spec);

	Bootstrap b = new Bootstrap();
	b.group(workerGroup);
	b.channel(NioSocketChannel.class);
	b.option(ChannelOption.SO_KEEPALIVE, true);
	b.option(ChannelOption.TCP_NODELAY, true);
	b.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
	b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec);
	b.handler(getChannelInitializer());

	ChannelFuture channelFuture = b.connect(controller.getRemoteAddress(replicaId));

	NettyClientServerSession ncss = new NettyClientServerSession(
			channelFuture.channel(), replicaId);
	sessionClientToReplica.put(replicaId, ncss);

	return channelFuture;
}
 
Example 5
Source File: NettyTransport.java    From jzab with Apache License 2.0 6 votes vote down vote up
public Sender(final String source, final String destination) {
  this.destination = destination;
  bootstrap = new Bootstrap();
  bootstrap.group(workerGroup);
  bootstrap.channel(NioSocketChannel.class);
  bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
  bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
  bootstrap.option(ChannelOption.TCP_NODELAY, true);
  bootstrap.handler(new ChannelInitializer<SocketChannel>() {
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
      if (isSslEnabled()) {
        SSLEngine engine = serverContext.createSSLEngine();
        engine.setUseClientMode(true);
        ch.pipeline().addLast(new SslHandler(engine));
      }
      // Inbound handlers.
      ch.pipeline().addLast("clientError", new ClientErrorHandler());
      // Outbound handlers.
      ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
    }
  });
}
 
Example 6
Source File: ConnectionPool.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public ConnectionPool(ClientConfigurationData conf, EventLoopGroup eventLoopGroup,
        Supplier<ClientCnx> clientCnxSupplier) throws PulsarClientException {
    this.eventLoopGroup = eventLoopGroup;
    this.clientConfig = conf;
    this.maxConnectionsPerHosts = conf.getConnectionsPerBroker();

    pool = new ConcurrentHashMap<>();
    bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup);
    bootstrap.channel(EventLoopUtil.getClientSocketChannelClass(eventLoopGroup));

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.getConnectionTimeoutMs());
    bootstrap.option(ChannelOption.TCP_NODELAY, conf.isUseTcpNoDelay());
    bootstrap.option(ChannelOption.ALLOCATOR, PulsarByteBufAllocator.DEFAULT);

    try {
        channelInitializerHandler = new PulsarChannelInitializer(conf, clientCnxSupplier);
        bootstrap.handler(channelInitializerHandler);
    } catch (Exception e) {
        log.error("Failed to create channel initializer");
        throw new PulsarClientException(e);
    }

    this.dnsResolver = new DnsNameResolverBuilder(eventLoopGroup.next()).traceEnabled(true)
            .channelType(EventLoopUtil.getDatagramChannelClass(eventLoopGroup)).build();
}
 
Example 7
Source File: ProxyToServerConnection.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
@Override
        protected Future<?> execute() {
            Bootstrap cb = new Bootstrap().group(proxyServer.getProxyToServerWorkerFor(transportProtocol));

            switch (transportProtocol) {
            case TCP:
                LOG.debug("Connecting to server with TCP");
                cb.channelFactory(new ChannelFactory<Channel>() {
                    @Override
                    public Channel newChannel() {
                        return new NioSocketChannel();
                    }
                });
                break;
            case UDT:
                LOG.debug("Connecting to server with UDT");
//                cb.channelFactory(NioUdtProvider.BYTE_CONNECTOR)
//                        .option(ChannelOption.SO_REUSEADDR, true);
//                break;
                throw new UnsupportedOperationException("unsupport udt proxy portocal");
            default:
                throw new UnknownTransportProtocolException(transportProtocol);
            }

            cb.handler(new ChannelInitializer<Channel>() {
                protected void initChannel(Channel ch) throws Exception {
                    initChannelPipeline(ch.pipeline(), initialRequest);
                };
            });
            cb.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                    proxyServer.getConnectTimeout());

            if (localAddress != null) {
                return cb.connect(remoteAddress, localAddress);
            } else {
                return cb.connect(remoteAddress);
            }
        }
 
Example 8
Source File: BilibiliDanmakuThread.java    From BakaDanmaku with MIT License 5 votes vote down vote up
@Override
public void doRun() {
    // 获取真实房间 ID
    String roomID = getRoomId(BakaDanmakuConfig.livePlatform.bilibiliRoom.liveRoom);

    // 提示,相关房间信息已经获取
    sendChatMessage("§8§l直播房间 ID 已经获取,ID 为 " + roomID);

    EventLoopGroup group = new NioEventLoopGroup();
    io.netty.util.Timer timer = new HashedWheelTimer();
    
    try {
        Bootstrap clientBootstrap = new Bootstrap();
        clientBootstrap.group(group);
        clientBootstrap.channel(NioSocketChannel.class);
        clientBootstrap.remoteAddress(LIVE_URL, PORT);
        clientBootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new BilibiliChannalInboundHandler(roomID));
            }
        });
        ChannelFuture channelFuture = clientBootstrap.connect().sync();
        timer.newTimeout(timeout -> {
            channelFuture.channel().writeAndFlush(sendDataPack(Unpooled.buffer(), 2, ""));
        }, 30000, TimeUnit.MILLISECONDS);
        channelFuture.channel().closeFuture().sync();
    } catch (InterruptedException ioe) {
        ioe.printStackTrace();
    } finally {
        try {
            timer.stop();
            group.shutdownGracefully().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
Example 9
Source File: ProxyHandlerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void test() throws Exception {
    final FailureTestHandler testHandler = new FailureTestHandler();
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class);
    b.resolver(NoopAddressResolverGroup.INSTANCE);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientHandlers);
            p.addLast(new LineBasedFrameDecoder(64));
            p.addLast(testHandler);
        }
    });

    boolean finished = b.connect(destination).channel().closeFuture().await(10, TimeUnit.SECONDS);
    finished &= testHandler.latch.await(10, TimeUnit.SECONDS);

    logger.debug("Recorded exceptions: {}", testHandler.exceptions);

    assertProxyHandlers(false);

    assertThat(testHandler.exceptions.size(), is(1));
    Throwable e = testHandler.exceptions.poll();
    assertThat(e, is(instanceOf(ProxyConnectException.class)));
    assertThat(String.valueOf(e), containsString(expectedMessage));
    assertThat(finished, is(true));
}
 
Example 10
Source File: UdpProtocol.java    From Okra with Apache License 2.0 5 votes vote down vote up
@Override
public Bootstrap createBootstrap() {
    bootstrap = new Bootstrap();
    bootstrap.channel(NioDatagramChannel.class);
    bootstrap.group(eventLoopGroup);
    bootstrap.handler(newChannelInitializer());
    return bootstrap;
}
 
Example 11
Source File: ProtocolClientsImpl.java    From ffwd with Apache License 2.0 5 votes vote down vote up
private AsyncFuture<ProtocolConnection> connectTCP(
    Logger log, Protocol protocol, ProtocolClient client, RetryPolicy policy
) {
    final Bootstrap b = new Bootstrap();

    b.group(worker);
    b.channel(NioSocketChannel.class);
    b.handler(client.initializer());

    b.option(ChannelOption.SO_KEEPALIVE, true);

    final String host = protocol.getAddress().getHostString();
    final int port = protocol.getAddress().getPort();

    final ProtocolConnection connection =
        new RetryingProtocolConnection(async, timer, log, policy, new ProtocolChannelSetup() {
            @Override
            public ChannelFuture setup() {
                return b.connect(host, port);
            }

            @Override
            public String toString() {
                return String.format("connect tcp://%s:%d", host, port);
            }
        });

    return async.resolved(connection);
}
 
Example 12
Source File: AbstractEndpointClient.java    From hermes with Apache License 2.0 5 votes vote down vote up
private Bootstrap createBootstrap(final Endpoint endpoint, final EndpointChannel endpointChannel) {
	Bootstrap bootstrap = new Bootstrap();
	bootstrap.group(m_eventLoopGroup);
	bootstrap.channel(NioSocketChannel.class);
	bootstrap.option(ChannelOption.SO_KEEPALIVE, true)//
	      .option(ChannelOption.TCP_NODELAY, true)//
	      .option(ChannelOption.SO_SNDBUF, m_config.getNettySendBufferSize())//
	      .option(ChannelOption.SO_RCVBUF, m_config.getNettyReceiveBufferSize());

	bootstrap.handler(new ChannelInitializer<SocketChannel>() {
		@Override
		public void initChannel(SocketChannel ch) throws Exception {

			ch.pipeline().addLast(
			      //
			      new DefaultNettyChannelOutboundHandler(), //
			      new NettyDecoder(), //
			      new MagicNumberAndLengthPrepender(), //
			      new NettyEncoder(), //
			      new IdleStateHandler(m_config.getEndpointChannelReadIdleTime(), //
			            m_config.getEndpointChannelWriteIdleTime(), //
			            m_config.getEndpointChannelMaxIdleTime()), //
			      new DefaultClientChannelInboundHandler(m_commandProcessorManager, endpoint, endpointChannel,
			            AbstractEndpointClient.this, m_config));
		}
	});

	return bootstrap;
}
 
Example 13
Source File: TimeClient.java    From codes-scratch-zookeeper-netty with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String host = "127.0.0.1";//args[0];
    int port = 8080;//Integer.parseInt(args[1]);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        Bootstrap b = new Bootstrap(); // (1)
        b.group(workerGroup); // (2)
        b.channel(NioSocketChannel.class); // (3)
        b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch)
                    throws Exception {
                ch.pipeline().addLast(new TimeClientHandler());
            }
        });

        // Start the client.
        ChannelFuture f = b.connect(host, port).sync(); // (5)

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }
}
 
Example 14
Source File: ProxyHandlerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void test() throws Exception {
    final SuccessTestHandler testHandler = new SuccessTestHandler();
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.AUTO_READ, ThreadLocalRandom.current().nextBoolean());
    b.resolver(NoopAddressResolverGroup.INSTANCE);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientHandlers);
            p.addLast(new LineBasedFrameDecoder(64));
            p.addLast(testHandler);
        }
    });

    boolean finished = b.connect(destination).channel().closeFuture().await(10, TimeUnit.SECONDS);

    logger.debug("Received messages: {}", testHandler.received);

    if (testHandler.exceptions.isEmpty()) {
        logger.debug("No recorded exceptions on the client side.");
    } else {
        for (Throwable t : testHandler.exceptions) {
            logger.debug("Recorded exception on the client side: {}", t);
        }
    }

    assertProxyHandlers(true);

    assertThat(testHandler.received.toArray(), is(new Object[] { "0", "1", "2", "3" }));
    assertThat(testHandler.exceptions.toArray(), is(EmptyArrays.EMPTY_OBJECTS));
    assertThat(testHandler.eventCount, is(expectedEventCount));
    assertThat(finished, is(true));
}
 
Example 15
Source File: OioEventLoopTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testTooManyClientChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Bootstrap cb = new Bootstrap();
    cb.channel(OioSocketChannel.class);
    cb.group(g);
    cb.handler(new ChannelInboundHandlerAdapter());
    ChannelFuture f2 = cb.connect(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    f2.await();

    assertThat(f2.cause(), is(instanceOf(ChannelException.class)));
    assertThat(f2.cause().getMessage().toLowerCase(), containsString("too many channels"));

    final CountDownLatch notified = new CountDownLatch(1);
    f2.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            notified.countDown();
        }
    });

    notified.await();
    g.shutdownGracefully();
}
 
Example 16
Source File: DatagramMulticastTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
public void testMulticast(Bootstrap sb, Bootstrap cb) throws Throwable {
    MulticastTestHandler mhandler = new MulticastTestHandler();

    sb.handler(new SimpleChannelInboundHandler<Object>() {
        @Override
        public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
            // Nothing will be sent.
        }
    });

    cb.handler(mhandler);

    sb.option(ChannelOption.IP_MULTICAST_IF, NetUtil.LOOPBACK_IF);
    sb.option(ChannelOption.SO_REUSEADDR, true);
    cb.option(ChannelOption.IP_MULTICAST_IF, NetUtil.LOOPBACK_IF);
    cb.option(ChannelOption.SO_REUSEADDR, true);

    Channel sc = sb.bind(newSocketAddress()).sync().channel();

    InetSocketAddress addr = (InetSocketAddress) sc.localAddress();
    cb.localAddress(addr.getPort());

    if (sc instanceof OioDatagramChannel) {
        // skip the test for OIO, as it fails because of
        // No route to host which makes no sense.
        // Maybe a JDK bug ?
        sc.close().awaitUninterruptibly();
        return;
    }
    DatagramChannel cc = (DatagramChannel) cb.bind().sync().channel();

    String group = "230.0.0.1";
    InetSocketAddress groupAddress = SocketUtils.socketAddress(group, addr.getPort());

    cc.joinGroup(groupAddress, NetUtil.LOOPBACK_IF).sync();

    sc.writeAndFlush(new DatagramPacket(Unpooled.copyInt(1), groupAddress)).sync();
    assertTrue(mhandler.await());

    // leave the group
    cc.leaveGroup(groupAddress, NetUtil.LOOPBACK_IF).sync();

    // sleep a second to make sure we left the group
    Thread.sleep(1000);

    // we should not receive a message anymore as we left the group before
    sc.writeAndFlush(new DatagramPacket(Unpooled.copyInt(1), groupAddress)).sync();
    mhandler.await();

    sc.close().awaitUninterruptibly();
    cc.close().awaitUninterruptibly();
}
 
Example 17
Source File: JNettyTcpConnector.java    From Jupiter with Apache License 2.0 4 votes vote down vote up
@Override
public JConnection connect(UnresolvedAddress address, boolean async) {
    setOptions();

    final Bootstrap boot = bootstrap();
    final SocketAddress socketAddress = InetSocketAddress.createUnresolved(address.getHost(), address.getPort());
    final JChannelGroup group = group(address);

    // 重连watchdog
    final ConnectionWatchdog watchdog = new ConnectionWatchdog(boot, timer, socketAddress, group) {

        @Override
        public ChannelHandler[] handlers() {
            return new ChannelHandler[] {
                    new FlushConsolidationHandler(JConstants.EXPLICIT_FLUSH_AFTER_FLUSHES, true),
                    this,
                    new IdleStateChecker(timer, 0, JConstants.WRITER_IDLE_TIME_SECONDS, 0),
                    idleStateTrigger,
                    CodecConfig.isCodecLowCopy() ? new LowCopyProtocolDecoder() : new ProtocolDecoder(),
                    encoder,
                    handler
            };
        }
    };

    ChannelFuture future;
    try {
        synchronized (bootstrapLock()) {
            boot.handler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(watchdog.handlers());
                }
            });

            future = boot.connect(socketAddress);
        }

        // 以下代码在synchronized同步块外面是安全的
        if (!async) {
            future.sync();
        }
    } catch (Throwable t) {
        throw new ConnectFailedException("Connects to [" + address + "] fails", t);
    }

    return new JNettyConnection(address, future) {

        @Override
        public void setReconnect(boolean reconnect) {
            if (reconnect) {
                watchdog.start();
            } else {
                watchdog.stop();
            }
        }
    };
}
 
Example 18
Source File: SocketCancelWriteTest.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
public void testCancelWrite(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    final TestHandler sh = new TestHandler();
    final TestHandler ch = new TestHandler();
    final ByteBuf a = Unpooled.buffer().writeByte('a');
    final ByteBuf b = Unpooled.buffer().writeByte('b');
    final ByteBuf c = Unpooled.buffer().writeByte('c');
    final ByteBuf d = Unpooled.buffer().writeByte('d');
    final ByteBuf e = Unpooled.buffer().writeByte('e');

    cb.handler(ch);
    sb.childHandler(sh);

    Channel sc = sb.bind().sync().channel();
    Channel cc = cb.connect().sync().channel();

    ChannelFuture f = cc.write(a);
    assertTrue(f.cancel(false));
    cc.writeAndFlush(b);
    cc.write(c);
    ChannelFuture f2 = cc.write(d);
    assertTrue(f2.cancel(false));
    cc.writeAndFlush(e);

    while (sh.counter < 3) {
        if (sh.exception.get() != null) {
            break;
        }
        if (ch.exception.get() != null) {
            break;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException ignore) {
            // Ignore.
        }
    }
    sh.channel.close().sync();
    ch.channel.close().sync();
    sc.close().sync();

    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
        throw sh.exception.get();
    }
    if (sh.exception.get() != null) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
        throw ch.exception.get();
    }
    if (ch.exception.get() != null) {
        throw ch.exception.get();
    }
    assertEquals(0, ch.counter);
    assertEquals(Unpooled.wrappedBuffer(new byte[]{'b', 'c', 'e'}), sh.received);
}
 
Example 19
Source File: AbstractNettyMulticastClient.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Override
public void connect() throws Exception {
    String interfaceIp = getSettings().getInterfaceIp();
    String mcastIp = getSettings().getMulticastIp();
    int mcastPort = getSettings().getMulticastPort();
    
    this.localNetworkInterface = NetworkInterface.getByInetAddress(InetAddress.getByName(interfaceIp));
    
    if (localNetworkInterface == null) {
        throw new ServiceException("Failed to resolve network interface via IP: " + interfaceIp);
    }
    
    this.multicastGroup = new InetSocketAddress(InetAddress.getByName(mcastIp), mcastPort);
    
    Bootstrap cb = new Bootstrap();
    cb.group(nioEventLoopGroup);
    cb.channelFactory(new NettyChannelFactory());
    cb.option(ChannelOption.SO_REUSEADDR, true);
    cb.option(ChannelOption.IP_MULTICAST_IF, localNetworkInterface);
    cb.option(ChannelOption.IP_MULTICAST_TTL, getSettings().getTtl());
    cb.localAddress(new InetSocketAddress(InetAddress.getByName(mcastIp), mcastPort));
    cb.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    cb.handler(NOOP_CHANNEL_INITIALIZER);
    
    Channel localChannel = cb.bind().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture bindFuture) throws Exception {
            if (!bindFuture.isSuccess()) {
                return;
            }
            DatagramChannel channel = (DatagramChannel)bindFuture.channel();
            
            ChannelFuture future;
            String sourceIP = getSettings().getSourceIp();
            if (sourceIP == null) {
                future = channel.joinGroup(multicastGroup, localNetworkInterface);
            } else {
                future = channel.joinGroup(multicastGroup.getAddress(), localNetworkInterface, InetAddress.getByName(sourceIP));
            }
            future.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
        }
    }).addListener(ChannelFutureListener.CLOSE_ON_FAILURE).syncUninterruptibly().channel();
    
    mainSession = createSession(localChannel);
    mainSession.withWriteLock(this::initChannel);
    mainSession.withWriteLock(this::initChannelCloseFuture);
}
 
Example 20
Source File: SocketSpdyEchoTest.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
private static void testSpdyEcho(
        ServerBootstrap sb, Bootstrap cb, final SpdyVersion version, boolean autoRead) throws Throwable {

    ByteBuf frames;
    switch (version) {
    case SPDY_3_1:
        frames = createFrames(3);
        break;
    default:
        throw new IllegalArgumentException("unknown version");
    }

    final SpdyEchoTestServerHandler sh = new SpdyEchoTestServerHandler(autoRead);
    final SpdyEchoTestClientHandler ch = new SpdyEchoTestClientHandler(frames.copy(), autoRead);

    sb.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel channel) throws Exception {
            channel.pipeline().addLast(
                    new SpdyFrameCodec(version),
                    sh);
        }
    });

    cb.handler(ch);

    Channel sc = sb.localAddress(0).bind().sync().channel();
    int port = ((InetSocketAddress) sc.localAddress()).getPort();

    Channel cc = cb.remoteAddress(NetUtil.LOCALHOST, port).connect().sync().channel();
    cc.writeAndFlush(frames);

    while (ch.counter < frames.writerIndex() - ignoredBytes) {
        if (sh.exception.get() != null) {
            break;
        }
        if (ch.exception.get() != null) {
            break;
        }

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            // Ignore.
        }
    }

    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
        throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
        throw ch.exception.get();
    }
}