io.netty.bootstrap.Bootstrap Java Examples

The following examples show how to use io.netty.bootstrap.Bootstrap. 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: StompClient.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("decoder", new StompSubframeDecoder());
                pipeline.addLast("encoder", new StompSubframeEncoder());
                pipeline.addLast("aggregator", new StompSubframeAggregator(1048576));
                pipeline.addLast("handler", new StompClientHandler());
            }
        });

        b.connect(HOST, PORT).sync().channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #2
Source File: CatNettyClient.java    From krpc with Apache License 2.0 6 votes vote down vote up
public void init() {

        timer = new Timer("krpc_cat_netty_timer");

        workerGroup = new NioEventLoopGroup(workerThreads, workThreadFactory);

        bootstrap = new Bootstrap();
        bootstrap.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("handler", CatNettyClient.this);
            }
        });
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.SO_REUSEADDR, true);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        // bootstrap.option(ChannelOption.SO_RCVBUF, 65536);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);

        log.info("cat netty client started");
    }
 
Example #3
Source File: EchoClient.java    From Lottor with MIT License 6 votes vote down vote up
public void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group) // 注册线程池
                .channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
                .remoteAddress(new InetSocketAddress(this.host, this.port)) // 绑定连接端口和host信息
                .handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        System.out.println("connected...");
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });
        System.out.println("created..");

        ChannelFuture cf = b.connect().sync(); // 异步连接服务器
        System.out.println("connected..."); // 连接完成

        cf.channel().closeFuture().sync(); // 异步等待关闭连接channel
        System.out.println("closed.."); // 关闭完成
    } finally {
        group.shutdownGracefully().sync(); // 释放线程池资源
    }
}
 
Example #4
Source File: OzymandiasClient.java    From archistar-core with GNU General Public License v2.0 6 votes vote down vote up
@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
private Channel connectServer(int port) throws Exception {

    final OzymandiasClientHandler handler = new OzymandiasClientHandler(this);

    Bootstrap b = new Bootstrap();
    b.group(group)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {

                    SSLEngine engine = SSLContextFactory.getClientContext().createSSLEngine();
                    engine.setUseClientMode(true);

                    ch.pipeline().addLast(
                            new SslHandler(engine),
                            new ObjectEncoder(),
                            new ObjectDecoder(OzymandiasServer.maxObjectSize, ClassResolvers.cacheDisabled(null)),
                            handler);
                }
            });

    return b.connect("127.0.0.1", port).sync().channel();
}
 
Example #5
Source File: DFSocketManager.java    From dfactor with MIT License 6 votes vote down vote up
protected ChannelFuture doTcpConntecSync(DFTcpClientCfg cfg, EventLoopGroup ioGroup, ChannelHandler handler){
	if(ioGroup == null){
		return null;
	}
	Bootstrap boot = new Bootstrap();
	boot.group(ioGroup)
		.option(ChannelOption.ALLOCATOR, 
				PooledByteBufAllocator.DEFAULT)
		.option(ChannelOption.SO_KEEPALIVE, cfg.isKeepAlive())
		.option(ChannelOption.SO_RCVBUF, cfg.getSoRecvBufLen())
		.option(ChannelOption.SO_SNDBUF, cfg.getSoSendBufLen())
		.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int)cfg.getConnTimeout())
		.option(ChannelOption.TCP_NODELAY, cfg.isTcpNoDelay())
		.handler(new TcpHandlerInit(false, cfg.getTcpProtocol(), 
				cfg.getTcpMsgMaxLength(), 0, 0, cfg.getWsUri(), null, 
				cfg.getDecoder(), cfg.getEncoder(), cfg.getUserHandler(), cfg.getSslCfg()
				, cfg.getReqData(), handler));
	if(ioGroup instanceof EpollEventLoopGroup){
		boot.channel(EpollSocketChannel.class);
	}else{
		boot.channel(NioSocketChannel.class);
	}
	ChannelFuture future = boot.connect(cfg.host, cfg.port);
	return future;
}
 
Example #6
Source File: NettyClient.java    From dubbo-remoting-netty4 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new Bootstrap();
    // config
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.group(WORKER_GROUP);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.handler(new ChannelInitializer() {
        public void initChannel(Channel ch) {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline channelPipeline = ch.pipeline();
            channelPipeline.addLast("decoder", adapter.getDecoder());
            channelPipeline.addLast("encoder", adapter.getEncoder());
            channelPipeline.addLast("handler", nettyHandler);
        }
    });

}
 
Example #7
Source File: EpollSocketTestPermutation.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public List<BootstrapFactory<Bootstrap>> clientSocket() {
    return Arrays.asList(
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(EPOLL_WORKER_GROUP).channel(EpollSocketChannel.class);
                }
            },
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(nioWorkerGroup).channel(NioSocketChannel.class);
                }
            }
    );
}
 
Example #8
Source File: ProxyFrontendHandler.java    From nano-proxy with Apache License 2.0 6 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) {
	final Channel inboundChannel = ctx.channel();
	// Start the connection attempt.
	Bootstrap b = new Bootstrap();
	b.group(inboundChannel.eventLoop())
			.channel(ctx.channel().getClass())
			.handler(new ProxyBackendHandler(inboundChannel, proxyDefinition))
			.option(ChannelOption.AUTO_READ, false);
	ChannelFuture f = b.connect(proxyDefinition.getRemoteHost(), proxyDefinition.getRemotePort());
	outboundChannel = f.channel();
	f.addListener(new ChannelFutureListener() {
		@Override
		public void operationComplete(ChannelFuture future) {
			if (future.isSuccess()) {
				// connection complete start to read first data
				inboundChannel.read();
			} else {
				// Close the connection if the connection attempt has failed.
				inboundChannel.close();
			}
		}
	});
}
 
Example #9
Source File: SocketCloseForciblyTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public void testCloseForcibly(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    sb.handler(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            SocketChannel childChannel = (SocketChannel) msg;
            childChannel.config().setSoLinger(0);
            childChannel.unsafe().closeForcibly();
        }
    }).childHandler(new ChannelInboundHandlerAdapter());

    cb.handler(new ChannelInboundHandlerAdapter());

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

    cb.connect(sc.localAddress()).channel().closeFuture().syncUninterruptibly();
    sc.close().sync();
}
 
Example #10
Source File: EpollSocketChannelTest.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Test
public void testTcpInfoReuse() throws Exception {
    EventLoopGroup group = new EpollEventLoopGroup(1);

    try {
        Bootstrap bootstrap = new Bootstrap();
        EpollSocketChannel ch = (EpollSocketChannel) bootstrap.group(group)
                .channel(EpollSocketChannel.class)
                .handler(new ChannelInboundHandlerAdapter())
                .bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        EpollTcpInfo info = new EpollTcpInfo();
        ch.tcpInfo(info);
        assertTcpInfo0(info);
        ch.close().syncUninterruptibly();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #11
Source File: NettyClient.java    From nuls-v2 with MIT License 6 votes vote down vote up
public NettyClient(Node node) {
    this.node = node;
    boot = new Bootstrap();

    AttributeKey<Node> key = null;
    synchronized (NettyClient.class) {
        if (AttributeKey.exists("node")) {
            key = AttributeKey.valueOf("node");
        } else {
            key = AttributeKey.newInstance("node");
        }
    }
    boot.attr(key, node);
    boot.group(worker)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.SO_SNDBUF, 128 * 1024)
            .option(ChannelOption.SO_RCVBUF, 128 * 1024)
            .option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNETCI_TIME_OUT)
            .handler(new NulsChannelInitializer<>(new ClientChannelHandler()));
}
 
Example #12
Source File: TimeClient.java    From JavaInterview with Apache License 2.0 6 votes vote down vote up
private void connect(String host, int port) throws Exception{
    //配置客户端NIO线程组
    EventLoopGroup group = new NioEventLoopGroup();

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new TimeClientHandler());
                }
            });

    //发起异步连接操作
    ChannelFuture cf = bootstrap.connect(host, port).sync();

    //等待 客户端链路关闭
    cf.channel().closeFuture().sync();
}
 
Example #13
Source File: AbstractRedisProxyServerTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
public ChannelFuture connect() throws Exception {

        startServer();
        Bootstrap b = new Bootstrap();
        b.group(new NioEventLoopGroup(1))
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();

                        p.addLast(new LoggingHandler(LogLevel.DEBUG));
                    }
                });
        return b.connect("127.0.0.1", config.frontendTcpPort());
    }
 
Example #14
Source File: ByteEchoPeerBase.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
public void run() throws Exception {
    final ThreadFactory connectFactory = new DefaultThreadFactory("rendezvous");
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1,
            connectFactory, NioUdtProvider.BYTE_PROVIDER);
    try {
        final Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(connectGroup)
                .channelFactory(NioUdtProvider.BYTE_RENDEZVOUS)
                .handler(new ChannelInitializer<UdtChannel>() {
                    @Override
                    protected void initChannel(UdtChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                new LoggingHandler(LogLevel.INFO),
                                new ByteEchoPeerHandler(messageSize));
                    }
                });
        final ChannelFuture future = bootstrap.connect(peerAddress, myAddress).sync();
        future.channel().closeFuture().sync();
    } finally {
        connectGroup.shutdownGracefully();
    }
}
 
Example #15
Source File: TCPClient.java    From krpc with MIT License 6 votes vote down vote up
/**
 * 初始化Bootstrap
 * 
 * @return
 */
public static final Bootstrap getBootstrap() {
	EventLoopGroup group = new NioEventLoopGroup();
	Bootstrap b = new Bootstrap();
	b.group(group).channel(NioSocketChannel.class);
	b.handler(new ChannelInitializer<Channel>() {
		@Override
		protected void initChannel(Channel ch) throws Exception {
			ChannelPipeline pipeline = ch.pipeline();
			pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
			pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
			pipeline.addLast("decoder", new ByteArrayDecoder());
			pipeline.addLast("encoder", new ByteArrayEncoder());
			pipeline.addLast("handler", new TcpClientHandler());
		}
	});
	return b;
}
 
Example #16
Source File: TrafficSimulationTests.java    From nano-proxy with Apache License 2.0 6 votes vote down vote up
@Test
public void simple() throws Exception {
	Bootstrap bootstrap = new Bootstrap();
	bootstrap.group(new NioEventLoopGroup(1))
			.channel(NioSocketChannel.class)
			.handler(new TrafficGeneratorClientHandler());
	final CountDownLatch latch = new CountDownLatch(1);
	bootstrap.connect("localhost",8010).addListener(new ChannelFutureListener() {
		@Override
		public void operationComplete(ChannelFuture future) throws Exception {
			if(future.isSuccess()){
				future.channel().writeAndFlush(Unpooled.buffer().capacity(256).writeZero(256));
			}else {
				System.err.println("Connection attempt failed");
				future.cause().printStackTrace();
			}
			latch.countDown();
		}
	});

latch.await();

}
 
Example #17
Source File: RxtxClient.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new OioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(RxtxChannel.class)
         .handler(new ChannelInitializer<RxtxChannel>() {
             @Override
             public void initChannel(RxtxChannel ch) throws Exception {
                 ch.pipeline().addLast(
                     new LineBasedFrameDecoder(32768),
                     new StringEncoder(),
                     new StringDecoder(),
                     new RxtxClientHandler()
                 );
             }
         });

        ChannelFuture f = b.connect(new RxtxDeviceAddress(PORT)).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #18
Source File: TestTCPServerSource.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private ChannelFuture startTcpClient(
    TCPServerSourceConfig configBean,
    EventLoopGroup workerGroup,
    byte[] data,
    boolean randomlySlice
) throws
    InterruptedException {
  ChannelFuture channelFuture;
  Bootstrap bootstrap = new Bootstrap();
  bootstrap.group(workerGroup);
  bootstrap.channel(NioSocketChannel.class);
  bootstrap.remoteAddress(new InetSocketAddress("localhost", Integer.parseInt(configBean.ports.get(0))));
  bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
  bootstrap.handler(new ChannelInitializer() {
    @Override
    protected void initChannel(Channel ch) throws Exception {
      ch.pipeline().addLast(new TCPServerSourceClientHandler(randomlySlice, data));
    }
  });

  // Start the client.
  channelFuture = bootstrap.connect().sync();

  return channelFuture;
}
 
Example #19
Source File: ProxyClient.java    From proxy with MIT License 6 votes vote down vote up
/**
 * 初始化 连接后端真正服务器
 */
private void initRealServerBoot() {

    //初始化
    realServerBootstrap = new Bootstrap();
    realServerGroup = new NioEventLoopGroup();


    realServerBootstrap.group(realServerGroup);
    realServerBootstrap.channel(NioSocketChannel.class);
    realServerBootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new TCPHandler());
            ch.pipeline().addLast(new HttpResponseDecoder());
            ch.pipeline().addLast(new HttpObjectAggregator(maxContentLength));
            ch.pipeline().addLast(new HttpSendHandler());
        }
    });
}
 
Example #20
Source File: UDPServerSocket.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
            bootstrap = new Bootstrap()
                    .channel(EPOLL ? EpollDatagramChannel.class : NioDatagramChannel.class)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(this)
                    .group(EPOLL ? new EpollEventLoopGroup() : new NioEventLoopGroup());
            this.logger.info("Epoll Status is " + EPOLL);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
Example #21
Source File: UptimeClient.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
static void connect(Bootstrap b) {
    b.connect().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.cause() != null) {
                handler.startTime = -1;
                handler.println("Failed to connect: " + future.cause());
            }
        }
    });
}
 
Example #22
Source File: TcpProtocolClient.java    From Okra with Apache License 2.0 5 votes vote down vote up
@Override
public Bootstrap createBootstrap() {
    bootstrap = new Bootstrap();
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.group(childGroup());
    bootstrap.handler(newChannelInitializer());

    return bootstrap;
}
 
Example #23
Source File: SocketTestPermutation.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public List<BootstrapComboFactory<ServerBootstrap, Bootstrap>> socket() {
    // Make the list of ServerBootstrap factories.
    List<BootstrapFactory<ServerBootstrap>> sbfs = serverSocket();

    // Make the list of Bootstrap factories.
    List<BootstrapFactory<Bootstrap>> cbfs = clientSocket();

    // Populate the combinations
    List<BootstrapComboFactory<ServerBootstrap, Bootstrap>> list = combo(sbfs, cbfs);

    // Remove the OIO-OIO case which often leads to a dead lock by its nature.
    list.remove(list.size() - 1);

    return list;
}
 
Example #24
Source File: EpollSocketTcpMd5Test.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testKeyMatch() throws Exception {
    server.config().setOption(EpollChannelOption.TCP_MD5SIG,
            Collections.<InetAddress, byte[]>singletonMap(NetUtil.LOCALHOST4, SERVER_KEY));

    EpollSocketChannel client = (EpollSocketChannel) new Bootstrap().group(GROUP)
            .channel(EpollSocketChannel.class)
            .handler(new ChannelInboundHandlerAdapter())
            .option(EpollChannelOption.TCP_MD5SIG,
                    Collections.<InetAddress, byte[]>singletonMap(NetUtil.LOCALHOST4, SERVER_KEY))
            .connect(server.localAddress()).syncUninterruptibly().channel();
    client.close().syncUninterruptibly();
}
 
Example #25
Source File: BootstrapTemplate.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){
	return new Bootstrap().group(loopGroup)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(handler)
			.bind(port);
}
 
Example #26
Source File: AbstractDatagramTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(Bootstrap bootstrap, Bootstrap bootstrap2, ByteBufAllocator allocator) {
    addr = new InetSocketAddress(
            NetUtil.LOCALHOST4, TestUtils.getFreePort());
    bootstrap.localAddress(addr);
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);
    bootstrap2.localAddress(0).remoteAddress(addr);
    bootstrap2.option(ChannelOption.ALLOCATOR, allocator);
}
 
Example #27
Source File: ObjectEchoClient.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                }
                p.addLast(
                        new ObjectEncoder(),
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoClientHandler());
            }
         });

        // Start the connection attempt.
        b.connect(HOST, PORT).sync().channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #28
Source File: MqttClient.java    From lannister with Apache License 2.0 5 votes vote down vote up
public MqttClient(String uri, boolean useInsecureTrustManagerFactory) throws URISyntaxException {
	this.bootstrap = new Bootstrap();
	this.uri = new URI(uri);
	this.trustManagerFactory = useInsecureTrustManagerFactory ? InsecureTrustManagerFactory.INSTANCE : null;
	this.sharedObject = new SharedObject();
	this.options = new ConnectOptions();
	this.currentMessageId = 0;
}
 
Example #29
Source File: SimpleSipStack.java    From sipstack with MIT License 5 votes vote down vote up
private Bootstrap createUDPListeningPoint(final SimpleChannelInboundHandler<SipMessageEvent> handler) {
    final Bootstrap b = new Bootstrap();
    b.group(this.udpGroup)
    .channel(NioDatagramChannel.class)
    .handler(new ChannelInitializer<DatagramChannel>() {
        @Override
        protected void initChannel(final DatagramChannel ch) throws Exception {
            final ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("decoder", new SipMessageDatagramDecoder());
            pipeline.addLast("encoder", new SipMessageEncoder());
            pipeline.addLast("handler", handler);
        }
    });
    return b;
}
 
Example #30
Source File: SocketConnectTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public void testLocalAddressAfterConnect(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    Channel serverChannel = null;
    Channel clientChannel = null;
    try {
        final Promise<InetSocketAddress> localAddressPromise = ImmediateEventExecutor.INSTANCE.newPromise();
        serverChannel = sb.childHandler(new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        localAddressPromise.setSuccess((InetSocketAddress) ctx.channel().localAddress());
                    }
                }).bind().syncUninterruptibly().channel();

        clientChannel = cb.handler(new ChannelInboundHandlerAdapter()).register().syncUninterruptibly().channel();

        assertNull(clientChannel.localAddress());
        assertNull(clientChannel.remoteAddress());

        clientChannel.connect(serverChannel.localAddress()).syncUninterruptibly().channel();
        assertLocalAddress((InetSocketAddress) clientChannel.localAddress());
        assertNotNull(clientChannel.remoteAddress());

        assertLocalAddress(localAddressPromise.get());
    } finally {
        if (clientChannel != null) {
            clientChannel.close().syncUninterruptibly();
        }
        if (serverChannel != null) {
            serverChannel.close().syncUninterruptibly();
        }
    }
}