public static SocketChannel open(SocketAddress address) throws Exception { SocketChannel socket = null; ChannelFuture future = boot.connect(address).sync(); if (future.isSuccess()) { future.channel().pipeline().get(BusinessHandler.class).latch.await(); socket = chManager.get(future.channel()); } if (null == socket) { throw new IOException("can't create socket!"); } return socket; }
public int start(final int port, final ChannelInitializer<? extends Channel> pipelineFactory) { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(group) .channel(NioServerSocketChannel.class) .childHandler(pipelineFactory); try { future = bootstrap.bind(port).sync(); SocketAddress socketAddress = future.channel().localAddress(); return ((InetSocketAddress) socketAddress).getPort(); } catch (InterruptedException e) { throw new MocoException(e); } }
public ChannelFuture start(InetSocketAddress address) { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(group) .channel(NioServerSocketChannel.class) .childHandler(createInitializer(channelGroup)); ChannelFuture future = bootstrap.bind(address); future.syncUninterruptibly(); channel = future.channel(); return future; }
public void start() { try { ChannelFuture channelFuture = serverBootstrap.bind().sync(); channelFuture.channel().closeFuture().sync(); } catch (Exception e) { logger.error("fail to start the MQTTServer." + e); } finally { logger.info("shutdown the MQTTServer"); shutdown(); } }
public void run() { try { channelFuture.channel().closeFuture().sync(); LOG.info("FileServer exiting"); } catch (InterruptedException e) { LOG.error("File server start got interrupted", e); } // NOTE: bootstrap is shutdown in stop() } };
public final void run(final String host, final int port, final ChannelHandler pipelineFactory) { EventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .remoteAddress(host, port) .option(ChannelOption.TCP_NODELAY, true) .handler(pipelineFactory); try { Channel channel = bootstrap.connect().sync().channel(); ChannelFuture future = channel.closeFuture().sync(); future.addListener(ChannelFutureListener.CLOSE); } catch (InterruptedException e) { throw new MocoException(e); } finally { group.shutdownGracefully(); } } }
@Test public void testInvalidServerResponse() throws Exception { ServerBootstrap bootstrap = createH2Server((dec, enc) -> new Http2EventAdapter() { @Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception { enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("xyz"), 0, false, ctx.newPromise()); ctx.flush(); } }); ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync(); try { Context ctx = vertx.getOrCreateContext(); ctx.runOnContext(v -> { client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", onFailure(err -> { assertOnIOContext(ctx); if (err instanceof NumberFormatException) { testComplete(); } })) .connectionHandler(conn -> conn.exceptionHandler(err -> fail())) .end(); }); await(); } finally { s.channel().close().sync(); } }
public void start(BufferedReader commandInputStream) { this.nioEventLoopGroup = new NioEventLoopGroup(1); try { Bootstrap b = new Bootstrap(); b.group(nioEventLoopGroup) .channel(NioSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE, true) .handler(getChannelInitializer()); // Start the connection attempt. this.channel = b.connect(host, port).sync().channel(); readUserInput(commandInputStream); } catch (UnresolvedAddressException uae) { log.error("Host name '{}' is invalid. Please make sure it is correct name.", host); } catch (ConnectTimeoutException cte) { log.error("Timeout exceeded when connecting to '{}:{}'. " + "Please make sure host available and port is open on target host.", host, port); } catch (IOException | InterruptedException e) { log.error("Error running client. Shutting down.", e); } catch (Exception e) { log.error(e); } finally { // The connection is closed automatically on shutdown. nioEventLoopGroup.shutdownGracefully(); } }
}); awaitLatch(latch); ServerBootstrap bs = new ServerBootstrap(); bs.group(context.nettyEventLoop()); bs.channelFactory(((VertxInternal)vertx).transport().serverChannelFactory(false)) ; bs.option(ChannelOption.SO_BACKLOG, 100); bs.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelFuture fut = bs.bind("localhost", 1234); try { fut.sync(); vertx.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> { assertTrue(ar.succeeded()); await(); } finally { fut.channel().close().sync();
@Override protected int initServer() throws InterruptedException { bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpServerCodec()); p.addLast(new TracingDispatchHandler()); p.addLast(new HelloWorldHandler()); } }); Channel ch = b.bind(0).sync().channel(); return ((InetSocketAddress) ch.localAddress()).getPort(); }
@Override protected void doOpen() throws Throwable { bootstrap = new ServerBootstrap(); bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true)); workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), new DefaultThreadFactory("NettyServerWorker", true)); channels = nettyServerHandler.getChannels(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE) .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childHandler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) throws Exception { ChannelFuture channelFuture = bootstrap.bind(getBindAddress()); channelFuture.syncUninterruptibly(); channel = channelFuture.channel();
@Override public void run() { try { ServerBootstrap bootstrap = getServerBootstrap(); LOGGER.info("Binding to the server port !!"); // Bind and start to accept incoming connections. ChannelFuture f = bootstrap.bind(_port).sync(); _channel = f.channel(); LOGGER.info("Server bounded to port :" + _port + ", Waiting for closing"); f.channel().closeFuture().sync(); LOGGER.info("Server boss channel is closed. Gracefully shutting down the server netty threads and pipelines"); } catch (Exception e) { LOGGER.error("Got exception in the main server thread. Stopping !!", e); } finally { _shutdownComplete.set(true); } }
/** * Connects to the node and returns only upon connection close */ public void connect(String host, int port, String remoteId, boolean discoveryMode) { try { ChannelFuture f = connectAsync(host, port, remoteId, discoveryMode); f.sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); logger.debug("Connection is closed"); } catch (Exception e) { if (discoveryMode) { logger.trace("Exception:", e); } else { if (e instanceof IOException) { logger.info("PeerClient: Can't connect to " + host + ":" + port + " (" + e.getMessage() + ")"); logger.debug("PeerClient.connect(" + host + ":" + port + ") exception:", e); } else { logger.error("Exception:", e); } } } }
public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress(host, port)) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new EchoClientHandler()); } }); ChannelFuture f = b.connect().sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } }
public Channel create(String bindAddr, int port) throws InterruptedException { NioEventLoopGroup group = new NioEventLoopGroup(1); Bootstrap b = new Bootstrap(); b.group(group) .channel(NioDatagramChannel.class) .handler(new ChannelInitializer<NioDatagramChannel>() { @Override public void initChannel(NioDatagramChannel ch) throws Exception { ch.pipeline().addLast(new PacketDecoder()); SimpleMessageHandler messageHandler = new SimpleMessageHandler(ch, nodeManager); nodeManager.setMessageSender(messageHandler); ch.pipeline().addLast(messageHandler); } }); return b.bind(bindAddr, port).sync().channel(); }