List of usage examples for io.netty.channel ChannelFuture channel
Channel channel();
From source file:com.github.wangshuwei5.server.NettyServer.java
License:Apache License
public void bind() throws Exception { // ??NIO/* ww w. jav a 2 s. c om*/ EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new NettyServerInitializer(SSLMODE.CSA.toString())); // ??? ChannelFuture f = b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync(); // ??? f.channel().closeFuture().sync(); System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT)); } finally { // ? bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.github.wolf480pl.ircd.IRCd.java
License:Open Source License
public static void main(String[] args) throws InterruptedException { Logger logger = LoggerFactory.getLogger(IRCd.class); logger.info("Starting IRCd"); ChannelFuture f = new NettyServer(new InetSocketAddress(6667), new IRCSessionHandler()).start(); f.sync(); // Wait for it to bind logger.info("IRCd started"); f.channel().closeFuture().sync(); // Wait for it to close }
From source file:com.github.wolf480pl.ircd.netty.NettyServer.java
License:Open Source License
public ChannelFuture start() { if (!started.compareAndSet(false, true)) { return null; }/*from ww w. j av a 2s . c om*/ ServerBootstrap bootstrap = new ServerBootstrap(); bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); IRCChannelInitializer initializer = new IRCChannelInitializer(handler); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(initializer) .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture future = bootstrap.bind(bindAddress); this.channel = future.channel(); return future; }
From source file:com.googlecode.protobuf.pro.duplex.client.DuplexTcpClientPipelineFactory.java
License:Apache License
/** * Creates a new client with the provided channel attributes to the remoteAddress. * @param remoteAddress/*from www. j av a 2 s . c om*/ * @param bootstrap * @param attributes * @return * @throws IOException */ public RpcClient peerWith(InetSocketAddress remoteAddress, Bootstrap bootstrap, Map<String, Object> attributes) throws IOException { if (remoteAddress == null) { throw new NullPointerException("remotedAddress"); } InetSocketAddress localAddress = null; if (clientInfo.getHostName() != null) { localAddress = new InetSocketAddress(clientInfo.getHostName(), clientInfo.getPort()); } ChannelFuture connectFuture = bootstrap.connect(remoteAddress, localAddress).awaitUninterruptibly(); if (!connectFuture.isSuccess()) { throw new IOException("Failed to connect to " + remoteAddress, connectFuture.cause()); } Channel channel = connectFuture.channel(); InetSocketAddress connectedAddress = (InetSocketAddress) channel.localAddress(); PeerInfo effectiveClientInfo = new PeerInfo( clientInfo.getHostName() == null ? connectedAddress.getHostName() : clientInfo.getHostName(), connectedAddress.getPort(), clientInfo.getPid()); ConnectRequest connectRequest = ConnectRequest.newBuilder() .setClientHostName(effectiveClientInfo.getHostName()).setClientPort(effectiveClientInfo.getPort()) .setClientPID(effectiveClientInfo.getPid()).setCorrelationId(correlationId.incrementAndGet()) .setCompress(isCompression()).build(); WirePayload payload = WirePayload.newBuilder().setConnectRequest(connectRequest).build(); if (log.isDebugEnabled()) { log.debug("Sending [" + connectRequest.getCorrelationId() + "]ConnectRequest."); } channel.writeAndFlush(payload); ClientConnectResponseHandler connectResponseHandler = (ClientConnectResponseHandler) channel.pipeline() .get(Handler.CLIENT_CONNECT); if (connectResponseHandler == null) { throw new IllegalStateException("No connectReponse handler in channel pipeline."); } ConnectResponse connectResponse = connectResponseHandler.getConnectResponse(connectResponseTimeoutMillis); if (connectResponse == null) { connectFuture.channel().close().awaitUninterruptibly(); throw new IOException( "No Channel response received before " + connectResponseTimeoutMillis + " millis timeout."); } if (connectResponse.hasErrorCode()) { connectFuture.channel().close().awaitUninterruptibly(); throw new IOException( "DuplexTcpServer CONNECT_RESPONSE indicated error " + connectResponse.getErrorCode()); } if (!connectResponse.hasCorrelationId()) { connectFuture.channel().close().awaitUninterruptibly(); throw new IOException("DuplexTcpServer CONNECT_RESPONSE missing correlationId."); } if (connectResponse.getCorrelationId() != connectRequest.getCorrelationId()) { connectFuture.channel().close().awaitUninterruptibly(); throw new IOException("DuplexTcpServer CONNECT_RESPONSE correlationId mismatch. TcpClient sent " + connectRequest.getCorrelationId() + " received " + connectResponse.getCorrelationId() + " from TcpServer."); } PeerInfo serverInfo = null; if (connectResponse.hasServerPID()) { serverInfo = new PeerInfo(remoteAddress.getHostName(), remoteAddress.getPort(), connectResponse.getServerPID()); } else { serverInfo = new PeerInfo(remoteAddress.getHostName(), remoteAddress.getPort()); } RpcClient rpcClient = new RpcClient(channel, effectiveClientInfo, serverInfo, connectResponse.getCompress(), getRpcLogger(), getExtensionRegistry()); if (attributes != null) { // transfer the input attributes to the channel before we state it's opened. for (Entry<String, Object> attr : attributes.entrySet()) { rpcClient.setAttribute(attr.getKey(), attr.getValue()); } } RpcClientHandler rpcClientHandler = completePipeline(rpcClient); rpcClientHandler.notifyOpened(); // register the rpcClient in the RpcClientRegistry if (!getRpcClientRegistry().registerRpcClient(rpcClient)) { log.warn("Client RpcClient already registered. Bug??"); } // channels remove themselves when closed. return rpcClient; }
From source file:com.graylog.splunk.output.senders.TCPSender.java
License:Open Source License
protected void createBootstrap(final EventLoopGroup workerGroup) { final Bootstrap bootstrap = new Bootstrap(); final SplunkSenderThread senderThread = new SplunkSenderThread(queue); bootstrap.group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) .remoteAddress(new InetSocketAddress(hostname, port)) .handler(new ChannelInitializer<SocketChannel>() { @Override/*w w w . j a va2s . co m*/ protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new StringEncoder()); ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { // we only send data, never read on the socket } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { senderThread.start(ctx.channel()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { LOG.info("Channel disconnected."); senderThread.stop(); scheduleReconnect(ctx.channel().eventLoop()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOG.error("Exception caught", cause); } }); } }); bootstrap.connect().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { LOG.info("Connected."); } else { LOG.error("Connection failed: {}", future.cause().getMessage()); scheduleReconnect(future.channel().eventLoop()); } } }); }
From source file:com.gxkj.demo.netty.discard.DiscardClient.java
License:Apache License
public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {//w w w. jav a2 s . c o m Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new DiscardClientHandler(firstMessageSize)); // Make the connection attempt. ChannelFuture f = b.connect(host, port).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } }
From source file:com.gxkj.demo.netty.discard.DiscardServer.java
License:Apache License
public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from w ww . ja v a 2s .c om*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new DiscardServerHandler()); } }); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(port).sync(); // Wait until the server socket is closed. // In this example, this does not happen, but you can do that to gracefully // shut down your server. f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
From source file:com.gxkj.demo.netty.echo.EchoClient.java
License:Apache License
public void run() throws Exception { // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try {/*w ww . ja v a 2 s . c o m*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( //new LoggingHandler(LogLevel.INFO), new EchoClientHandler(firstMessageSize)); } }); // Start the client. ChannelFuture f = b.connect(host, port).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }
From source file:com.gxkj.demo.netty.echo.EchoServer.java
License:Apache License
public void run() throws Exception { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {//from w w w .j a va 2 s . c om ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( //new LoggingHandler(LogLevel.INFO), new EchoServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(port).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.gxkj.demo.netty.proxy.HexDumpProxyBackendHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { @Override/*from w w w . j a v a 2 s. co m*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { ctx.channel().read(); } else { future.channel().close(); } } }); }