/** * 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); } } } }
/** * Reopens the listening channel for this node. If the channel was already open, has no effect and * future completes immediately. * * @return future that completes when listening channel is reopened. */ private CompletableFuture<Void> rebind() { if (this.channel.get().isOpen()) { // already accepting... return CompletableFuture.completedFuture(null); } CompletableFuture<Void> future = new CompletableFuture<>(); ChannelFuture bindFuture = bootstrap.bind(this.getAddress()); bindFuture.addListener( (ChannelFutureListener) channelFuture -> { if (channelFuture.isSuccess()) { channelFuture.channel().attr(Server.HANDLER).set(this); logger.debug("Bound {} to {}", BoundNode.this, channelFuture.channel()); future.complete(null); channel.set(channelFuture.channel()); } else { // If failed, propagate it. future.completeExceptionally( new BindNodeException(BoundNode.this, getAddress(), channelFuture.cause())); } }); return future; }
/** * Adds a channel that listens locally */ public SocketAddress addLocalEndpoint() { ChannelFuture channelfuture; synchronized (this.endpoints) { channelfuture = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(LocalServerChannel.class)).childHandler(new ChannelInitializer<Channel>() { protected void initChannel(Channel p_initChannel_1_) throws Exception { NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.SERVERBOUND); networkmanager.setNetHandler(new NetHandlerHandshakeMemory(NetworkSystem.this.mcServer, networkmanager)); NetworkSystem.this.networkManagers.add(networkmanager); p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager); } }).group((EventLoopGroup)SERVER_NIO_EVENTLOOP.getValue()).localAddress(LocalAddress.ANY)).bind().syncUninterruptibly(); this.endpoints.add(channelfuture); } return channelfuture.channel().localAddress(); }
/** * Adds a channel that listens locally */ public SocketAddress addLocalEndpoint() { ChannelFuture channelfuture; synchronized (this.endpoints) { channelfuture = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(LocalServerChannel.class)).childHandler(new ChannelInitializer<Channel>() { protected void initChannel(Channel p_initChannel_1_) throws Exception { NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.SERVERBOUND); networkmanager.setNetHandler(new NetHandlerHandshakeMemory(NetworkSystem.this.mcServer, networkmanager)); NetworkSystem.this.networkManagers.add(networkmanager); p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager); } }).group((EventLoopGroup)eventLoops.getValue()).localAddress(LocalAddress.ANY)).bind().syncUninterruptibly(); this.endpoints.add(channelfuture); } return channelfuture.channel().localAddress(); }
/** * Establishes a new socket connection with connection test */ protected void setupWithTest() { ChannelFuture future = boot.connect(uri.host(), port); future.addListener( new GenericFutureListener<ChannelFuture>() { public void operationComplete(ChannelFuture f) { if (f.isSuccess()) { channel = (HTTPChannel) f.channel(); testConnection(); onTestBell.promise(onConnectBell); } else { onConnectBell.ring(f.cause()); } } }); }
/** * Shuts down all open endpoints (with immediate effect?) */ public void terminateEndpoints() { this.isAlive = false; for (ChannelFuture channelfuture : this.endpoints) { try { channelfuture.channel().close().sync(); } catch (InterruptedException var4) { logger.error("Interrupted whilst closing channel"); } } }
/** * Shuts down all open endpoints (with immediate effect?) */ public void terminateEndpoints() { this.isAlive = false; for (ChannelFuture channelfuture : this.endpoints) { try { channelfuture.channel().close().sync(); } catch (InterruptedException var4) { LOGGER.error("Interrupted whilst closing channel"); } } }
@Override public ProtocolFuture write(byte[] data) { this.lastActive = System.currentTimeMillis(); if (!isClosed()) { ChannelFuture future = channel.write(data); return new ProtocolFuture() { @Override public boolean isSuccess() { return future.isSuccess(); } @Override public boolean isDone() { return future.isDone(); } }; } else { return ProtocolFuture.ERRORFUTURE; } }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; String sentData = in.toString(CharsetUtil.UTF_8); String returnee = sentData + "-::=::-" + "{}"; RequestProcessor reprocessor = EchoServer.process(sentData); if (reprocessor != null) returnee = sentData + "-::=::-" + reprocessor.getProcessedData(); ChannelFuture f = ctx.writeAndFlush(Unpooled.copiedBuffer(returnee, CharsetUtil.UTF_8)).sync(); if (!f.isSuccess()) try { throw f.cause(); } catch (Throwable throwable) { throwable.printStackTrace(); } }
public static void main(String[] args) throws IOException, InterruptedException { Bootstrap b = new Bootstrap(); b.group(new NioEventLoopGroup()) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) throws Exception { } }); b.connect("localhost", 8090).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().write(Unpooled.buffer().writeBytes("123".getBytes())); future.channel().flush(); future.channel().close(); } } }); }
private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.writeAndFlush(res); if (!isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
private TransportAddress bindAddress(final InetAddress hostAddress) { final AtomicReference<Exception> lastException = new AtomicReference<>(); final AtomicReference<InetSocketAddress> boundSocket = new AtomicReference<>(); boolean success = port.iterate(portNumber -> { try { synchronized (serverChannels) { ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(hostAddress, portNumber)).sync(); serverChannels.add(future.channel()); boundSocket.set((InetSocketAddress) future.channel().localAddress()); } } catch (Exception e) { lastException.set(e); return false; } return true; }); if (!success) { throw new BindHttpException("Failed to bind to [" + port.getPortRangeString() + "]", lastException.get()); } if (logger.isDebugEnabled()) { logger.debug("Bound http to address {{}}", NetworkAddress.format(boundSocket.get())); } return new TransportAddress(boundSocket.get()); }
public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress(this.host, this.port)) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { System.out.println("connected server..."); ch.pipeline().addLast(new ByteArrayEncoder()); ch.pipeline().addLast(new ByteArrayDecoder()); ch.pipeline().addLast(new EchoClientHandler()); } }); ChannelFuture cf = b.connect().sync(); cf.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } }
/** * Start the server * * @param port The port on which the server listen to */ public void run(final int port) { final EventLoopGroup bossGroup = new NioEventLoopGroup(); final EventLoopGroup workerGroup = new NioEventLoopGroup(); try { final ServerBootstrap bootstrap = new ServerBootstrap() .group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ServerInitializer()) .childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.TCP_NODELAY, true); final ChannelFuture f = bootstrap.bind(port).sync(); LOGGER.info("NettyServer: running on port {}", port); f.channel().closeFuture().sync(); } catch (final InterruptedException e) { LOGGER.error("NettyServer: an error occurred while running: {}", e.getMessage()); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
@Override public void channelRead(ChannelHandlerContext ctx, Object e) throws Exception { if (e instanceof ServletResponse) { logger.info("Handler async task..."); HttpServletResponse response = (HttpServletResponse) e; Runnable task = ThreadLocalAsyncExecutor.pollTask(response); task.run(); // write response... ChannelFuture future = ctx.channel().writeAndFlush(response); String keepAlive = response.getHeader(CONNECTION.toString()); if (null != keepAlive && HttpHeaderValues.KEEP_ALIVE.toString().equalsIgnoreCase(keepAlive)) { future.addListener(ChannelFutureListener.CLOSE); } } else { ctx.fireChannelRead(e); } }
@Override public void channelRead(final ChannelHandlerContext context, Object msg) { if(client.getInbound().isActive()) { client.getInbound().writeAndFlush(msg).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { context.channel().read(); } else { future.channel().close(); } } }); } else { client.getOutbound().close(); } }
public static int writeBack(Channel channel, boolean isSuccess, String resultStr, boolean isKeepAlive) { ByteBuf content = Unpooled.copiedBuffer(resultStr, Constants.DEFAULT_CHARSET); HttpResponseStatus status; if (isSuccess) { status = HttpResponseStatus.OK; } else { status = HttpResponseStatus.INTERNAL_SERVER_ERROR; } FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, status, content); //logger.info("result str:{}", resultStr); res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); HttpHeaders.setContentLength(res, content.readableBytes()); try { ChannelFuture f = channel.writeAndFlush(res); if (isKeepAlive) { HttpHeaders.setKeepAlive(res, true); } else { HttpHeaders.setKeepAlive(res, false);//set keepalive closed f.addListener(ChannelFutureListener.CLOSE); } } catch (Exception e2) { logger.warn("Failed to send HTTP response to remote, cause by:", e2); } return content.readableBytes(); }
public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.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 = bootstrap.connect().sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } }
/** * Convenience method to convert a {@link ChannelFuture} into a {@link CompletableFuture} * * @param future future to convert. * @return converted future. */ public static CompletableFuture<Void> completable(ChannelFuture future) { CompletableFuture<Void> cf = new CompletableFuture<>(); future.addListener( (ChannelFutureListener) future1 -> { if (future1.isSuccess()) { cf.complete(null); } else { cf.completeExceptionally(future1.cause()); } }); return cf; }
/** * Broker主动回查Producer事务状态,Oneway */ public void checkProducerTransactionState( final Channel channel, final CheckTransactionStateRequestHeader requestHeader, final SelectMappedBufferResult selectMappedBufferResult) { RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CHECK_TRANSACTION_STATE, requestHeader); request.markOnewayRPC(); try { FileRegion fileRegion = new OneMessageTransfer(request.encodeHeader(selectMappedBufferResult.getSize()), selectMappedBufferResult); channel.writeAndFlush(fileRegion).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { selectMappedBufferResult.release(); if (!future.isSuccess()) { log.error("invokeProducer failed,", future.cause()); } } }); } catch (Throwable e) { log.error("invokeProducer exception", e); selectMappedBufferResult.release(); } }
private static CompletableFuture<Void> closeChannelGroup( ChannelGroup channelGroup, CloseType closeType) { switch (closeType) { case DISCONNECT: return completable(channelGroup.disconnect()); default: return CompletableFuture.allOf( channelGroup .stream() .map( c -> { CompletableFuture<Void> f; Function<SocketChannel, ChannelFuture> shutdownMethod = closeType == CloseType.SHUTDOWN_READ ? SocketChannel::shutdownInput : SocketChannel::shutdownOutput; if (c instanceof SocketChannel) { f = completable(shutdownMethod.apply((SocketChannel) c)); } else { logger.warn( "Got {} request for non-SocketChannel {}, disconnecting instead.", closeType, c); f = completable(c.disconnect()); } return f; }) .collect(Collectors.toList()) .toArray(new CompletableFuture[] {})); } }
@Override public void operationComplete(ChannelFuture future) throws Exception { final String msg = String.format("[%s]: Channel closed %s", rpcConfig.getName(), clientConnection.getName()); final ChannelClosedException ex = future.cause() != null ? new ChannelClosedException(msg, future.cause()) : new ChannelClosedException(msg); logger.info(msg); clientConnection.channelClosed(ex); }
@Override public boolean start() { boolean result = false; do { TcpRouteDefinition route = definition.getRoute(); if(null == route) { break; } if(route.getAddress() == null || route.getAddress().isEmpty()) { break; } if(route.getPort() == -1) { break; } try { Bootstrap bootstrap = new Bootstrap(); bootstrap.channel(inbound.getClass()); bootstrap.group(inbound.eventLoop()); bootstrap.handler(new TcpProxyClientChannelInitializer(definition, this)); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.AUTO_READ, false); ChannelFuture future = bootstrap.connect(route.getAddress(), route.getPort()); //forwarder = future.sync().channel(); outbound = future.channel(); future.addListener(listener); } catch (Exception e) { log.error("Failed starting tcp proxy client.", e); outbound = null; break; } result = true; } while (false); return result; }
public void start() throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); 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 FileServerHandlerInitializer()); // Start the server. ChannelFuture f = b.bind(getHostAddress(), PORT).sync(); // System.out.println("server is started "+f.isSuccess()); setStarted(true); // 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(); } }
public void start() { Configuration config = Configuration.INSTANCE; InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE); EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline() .addLast("logging", new LoggingHandler(LogLevel.DEBUG)) .addLast(new XConnectHandler()); if (config.getReadLimit() != 0 || config.getWriteLimit() != 0) { socketChannel.pipeline().addLast( new GlobalTrafficShapingHandler(Executors.newScheduledThreadPool(1), config.getWriteLimit(), config.getReadLimit()) ); } } }); log.info("\tStartup {}-{}-server [{}]", Constants.APP_NAME, Constants.APP_VERSION, config.getProtocol()); new Thread(() -> new UdpServer().start()).start(); ChannelFuture future = bootstrap.bind(config.getHost(), config.getPort()).sync(); future.addListener(future1 -> log.info("\tTCP listening at {}:{}...", config.getHost(), config.getPort())); future.channel().closeFuture().sync(); } catch (Exception e) { log.error("\tSocket bind failure ({})", e.getMessage()); } finally { log.info("\tShutting down and recycling..."); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); Configuration.shutdownRelays(); } System.exit(0); }
public static void closeChannel(Channel channel) { final String addrRemote = RemotingHelper.parseChannelRemoteAddr(channel); channel.close().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { logger.info("closeChannel: close the connection to remote address[{}] result: {}", addrRemote, future.isSuccess()); } }); }
protected ChannelFuture doBooterBind(InetSocketAddress local,final ChannelHandler fixedHandler) { ChannelFuture cf; synchronized (booter) { final CountDownLatch latch=new CountDownLatch(1); LoggerHandler loggerHandler=null;//server接收处理链路的日志记录器 LogLevel level=config.getLevel(); if(level!=null) { loggerHandler=new LoggerHandler(level); } ChannelHandler childHandler=initLogHandlerAdapter(fixedHandler); booter.handler(loggerHandler).childHandler(childHandler); cf=booter.bind(local); cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { latch.countDown(); } }); try { latch.await(3,TimeUnit.SECONDS); } catch (Exception e) { log.error(e.getMessage(),e); } } return cf; }
@Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isDone() && future.isSuccess()) { set(new NettyRpcChannel(future.channel())); } else if (future.isDone() && future.cause() != null) { setException(future.cause()); } else if (future.isDone() && future.isCancelled()) { cancel(false); } }
@Override public Connection connect(Address address, Consumer<TransportChannel> successEvent) { Bootstrap bootstrap = bootstrap(); final SocketAddress socketAddress = InetSocketAddress.createUnresolved(address.getHost(), address.getPort()); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline() .addLast(new Encoder(serializer)) .addLast(new Decoder(serializer)) .addLast(new ConsumerHandler()); } }); ChannelFuture connectChannelFuture = bootstrap.connect(socketAddress); connectChannelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { TransportChannel transportChannel = NettyChannel.getInstance(future.channel()); successEvent.accept(transportChannel); } } }); return new NettyConnection(connectChannelFuture); }
public void server(int port) throws Exception { final ByteBuf buf = Unpooled.unreleasableBuffer( Unpooled.copiedBuffer("Hi!\r\n", Charset.forName("UTF-8"))); EventLoopGroup group = new OioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(group) .channel(OioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(buf.duplicate()).addListener(ChannelFutureListener.CLOSE); } }); } }); ChannelFuture f = b.bind().sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } }
public ChannelFuture start() throws InterruptedException { workerGroup = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup).channel(NioDatagramChannel.class).handler(new ServerChannelInitializer()); ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(port)).syncUninterruptibly(); channel = channelFuture.channel(); return channelFuture; }
public static void closeChannel(Channel channel) { final String addrRemote = RemotingHelper.parseChannelRemoteAddr(channel); channel.close().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { log.info("closeChannel: close the connection to remote address[{}] result: {}", addrRemote, future.isSuccess()); } }); }
/** * Request to stream the data with the given stream ID from the remote end. * * @param streamId The stream to fetch. * @param callback Object to call with the stream data. */ public void stream(final String streamId, final StreamCallback callback) { final long startTime = System.currentTimeMillis(); if (logger.isDebugEnabled()) { logger.debug("Sending stream request for {} to {}", streamId, getRemoteAddress(channel)); } // Need to synchronize here so that the callback is added to the queue and the RPC is // written to the socket atomically, so that callbacks are called in the right order // when responses arrive. synchronized (this) { handler.addStreamCallback(callback); channel.writeAndFlush(new StreamRequest(streamId)).addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { long timeTaken = System.currentTimeMillis() - startTime; if (logger.isTraceEnabled()) { logger.trace("Sending request for {} to {} took {} ms", streamId, getRemoteAddress(channel), timeTaken); } } else { String errorMsg = String.format("Failed to send request for %s to %s: %s", streamId, getRemoteAddress(channel), future.cause()); logger.error(errorMsg, future.cause()); channel.close(); try { callback.onFailure(streamId, new IOException(errorMsg, future.cause())); } catch (Exception e) { logger.error("Uncaught exception in RPC response callback handler!", e); } } } }); } }
public void closeEndpoints() { for(ChannelFuture ch : this.endpoints) { try { ch.channel().close().sync(); } catch (InterruptedException e) { e.printStackTrace(); } } }
public void run() { ServerBootstrap b = new ServerBootstrap();// 引导辅助程序 bossGroup = new NioEventLoopGroup(BIZGROUPSIZE); workerGroup = new NioEventLoopGroup(BIZTHREADSIZE); try { b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class);// 设置nio类型的channel b.childHandler(new ChannelInitializer<SocketChannel>() {// 有连接到达时会创建一个channel protected void initChannel(SocketChannel ch) throws Exception { logger.debug("客户端:{} 初始化", ch.remoteAddress()); // pipeline管理channel中的Handler,在channel队列中添加一个handler来处理业务 ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4)); ch.pipeline().addLast("decoder", msgPackDecode); ch.pipeline().addLast("encoder", msgPackEncode); ch.pipeline().addLast(serverHandler); } }); b.option(ChannelOption.SO_BACKLOG, 128); b.childOption(ChannelOption.SO_KEEPALIVE, true); logger.info("server start : {}", port); ChannelFuture f = b.bind(port).sync();// 配置完成,开始绑定server,通过调用sync同步方法阻塞直到绑定成功 channel = f.channel(); f.channel().closeFuture().sync();// 应用程序会一直等待,直到channel关闭 } catch (Exception e) { e.printStackTrace(); } }
private void onSocksSuccess(ChannelHandlerContext ctx, Socks4CommandRequest request) { Address serverAddr = new Address(request.dstAddr(), request.dstPort()); createServerChannel(ctx, serverAddr).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { ConnectionInfo newConnectionInfo = new ConnectionInfo( connectionInfo.getClientAddr(), serverAddr); ctx.writeAndFlush(new DefaultSocks4CommandResponse( Socks4CommandStatus.SUCCESS, request.dstAddr(), request.dstPort())); onServerConnected(ctx, newConnectionInfo, future.channel()); } else { ctx.channel().writeAndFlush(new DefaultSocks4CommandResponse( Socks4CommandStatus.REJECTED_OR_FAILED, request.dstAddr(), request.dstPort())); ctx.close(); } } }); }
/** *@description 连接服务器 *@time 创建时间:2017年7月21日下午4:15:50 *@param host *@param port *@throws InterruptedException *@author dzn */ public void connect(String host, int port) throws InterruptedException{ EventLoopGroup group = new NioEventLoopGroup(); try{ //netty客户端 Bootstrap boot = new Bootstrap(); boot.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { //对输入数据进行业务逻辑处理 ch.pipeline().addLast(new ErrorTimeClientHandler()); } }); //使用netty客户端连接netty服务器 ChannelFuture future = boot.connect(host, port).sync(); //等待客户端Channel关闭 future.channel().closeFuture().sync(); }finally{ group.shutdownGracefully(); } }
@Override public void operationComplete(ChannelFuture future) throws Exception { boolean removed = openChannels.remove(future.channel()); if (removed) { openChannelsMetric.dec(); } if (logger.isTraceEnabled()) { logger.trace("channel closed: {}", future.channel()); } }
/** * Opens the connection to the given serial port. * * @param address The serial port, must not be null. * @throws IOException if opening of the channel fails. */ public void open(RxtxDeviceAddress address) throws IOException { requireNonNull(address); lock.lock(); try { checkIfChannelIsClose(); Log.debug(SERIAL, "Opening channel at serial port '" + address.value() + "'."); ChannelFuture future = bootstrap.connect(address).syncUninterruptibly(); if (!future.isSuccess()) { fireOnError(); throw new IOException("Serial channel couldn't be opened!"); } Log.debug(SERIAL, "Serial channel was successfully opened."); currentChannel = future.channel(); } catch (Exception e) { throw new IOException("Can not connect to '"+address.value()+"'!", e); } finally { lock.unlock(); } }