List of usage examples for io.netty.channel ChannelFuture channel
Channel channel();
From source file:books.netty.protocol.file.FileServer.java
License:Apache License
public void run(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {//ww w . j a va 2 s. co m ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() { /* * (non-Javadoc) * * @see * io.netty.channel.ChannelInitializer#initChannel(io * .netty.channel.Channel) */ public void initChannel(SocketChannel ch) { ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(1024), new StringDecoder(CharsetUtil.UTF_8), new FileServerHandler()); } }); ChannelFuture f = b.bind(port).sync(); System.out.println("Start file server at port : " + port); f.channel().closeFuture().sync(); } finally { // ? bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:books.netty.protocol.http.fileServer.HttpFileServer.java
License:Apache License
public void run(final int port, final String url) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from w w w. ja v a2 s .c om*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { // ?? ch.pipeline().addLast("http-decoder", new HttpRequestDecoder()); // ?? ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); // ?? ch.pipeline().addLast("http-encoder", new HttpResponseEncoder()); // ????? ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); ch.pipeline().addLast("fileServerHandler", new HttpFileServerHandler(url)); } }); // ChannelFuture future = b.bind("192.168.1.102", port).sync(); ChannelFuture future = b.bind(port).sync(); System.out.println("HTTP??? : " + "http://127.0.0.1:" + port + url); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:books.netty.protocol.http.xml.client.HttpXmlClient.java
License:Apache License
public void connect(int port) throws Exception { // ?NIO//from w w w .ja v a 2s .co m EventLoopGroup group = new NioEventLoopGroup(); try { 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) { ch.pipeline().addLast("http-decoder", new HttpResponseDecoder()); ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); // XML? ch.pipeline().addLast("xml-decoder", new HttpXmlResponseDecoder(Order.class, true)); ch.pipeline().addLast("http-encoder", new HttpRequestEncoder()); ch.pipeline().addLast("xml-encoder", new HttpXmlRequestEncoder()); ch.pipeline().addLast("xmlClientHandler", new HttpXmlClientHandle()); } }); // ?? ChannelFuture f = b.connect(new InetSocketAddress(port)).sync(); // f.channel().closeFuture().sync(); } finally { // NIO group.shutdownGracefully(); } }
From source file:books.netty.protocol.http.xml.server.HttpXmlServer.java
License:Apache License
public void run(final int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*ww w .j a v a 2s. co m*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast("http-decoder", new HttpRequestDecoder()); ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("xml-decoder", new HttpXmlRequestDecoder(Order.class, true)); ch.pipeline().addLast("http-encoder", new HttpResponseEncoder()); ch.pipeline().addLast("xml-encoder", new HttpXmlResponseEncoder()); ch.pipeline().addLast("xmlServerHandler", new HttpXmlServerHandler()); } }); ChannelFuture future = b.bind(new InetSocketAddress(port)).sync(); System.out.println("HTTP??? : " + "http://localhost:" + port); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:books.netty.protocol.netty.client.NettyClient.java
License:Apache License
public void connect(int port, String host) throws Exception { // ?NIO//from ww w .j av a 2 s. com try { 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 NettyMessageDecoder(1024 * 1024, 4, 4)); ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder()); ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50)); ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler()); ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler()); } }); // ?? ChannelFuture future = b.connect(new InetSocketAddress(host, port), new InetSocketAddress(NettyConstant.LOCALIP, NettyConstant.LOCAL_PORT)).sync(); future.channel().closeFuture().sync(); } finally { // ???????? executor.execute(new Runnable() { @Override public void run() { try { TimeUnit.SECONDS.sleep(1); try { connect(NettyConstant.PORT, NettyConstant.REMOTEIP);// ??? } catch (Exception e) { e.printStackTrace(); } } catch (InterruptedException e) { e.printStackTrace(); } } }); } }
From source file:bridgempp.bot.wrapper.BotWrapper.java
private static void botInitialize(File botConfig) { try {/*from ww w.j av a 2s .c om*/ Properties botProperties = new Properties(); if (!botConfig.exists()) { botConfig.createNewFile(); } botProperties.load(new FileInputStream(botConfig)); String botClass = botProperties.getProperty("botClass"); if (botClass == null) { writeDefaultConfig(botProperties); throw new UnsupportedOperationException( "Bot Class is null, cannot execute BridgeMPP server commands"); } Bot bot = (Bot) Class.forName(botClass).newInstance(); bot.initializeBot(); String serverAddress = botProperties.getProperty("serverAddress"); int portNumber = Integer.parseInt(botProperties.getProperty("serverPort")); if (serverAddress == null) { writeDefaultConfig(botProperties); throw new UnsupportedOperationException( "Server Address is null, cannot execute BridgeMPP server commands"); } ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(serverAddress, portNumber)); byte[] protocol = new byte[1]; protocol[0] = 0x32; channelFuture.await(); channelFuture.channel().writeAndFlush(Unpooled.wrappedBuffer(protocol)); channelFuture.channel().pipeline().addLast("frameDecoder", new ProtobufVarint32FrameDecoder()); channelFuture.channel().pipeline().addLast("protobufDecoder", new ProtobufDecoder(ProtoBuf.Message.getDefaultInstance())); channelFuture.channel().pipeline().addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender()); channelFuture.channel().pipeline().addLast("protobufEncoder", new ProtobufEncoder()); channelFuture.channel().pipeline().addLast(new IncommingMessageHandler(bot)); bot.channelFuture = channelFuture; bot.setProperties(botProperties); String serverKey = botProperties.getProperty("serverKey"); if (serverKey == null) { writeDefaultConfig(botProperties); throw new UnsupportedOperationException( "Server Key is null, cannot execute BridgeMPP server commands"); } printCommand("!usekey " + serverKey, bot); String botAlias = botProperties.getProperty("botname"); if (botAlias != null) { printCommand("!createalias " + botAlias, bot); } bot.name = botAlias; String[] groups = botProperties.getProperty("groups").split("; "); for (int i = 0; i < groups.length; i++) { printCommand("!subscribegroup " + groups[i], bot); } System.out.println("Joined " + groups.length + " groups"); } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException | InterruptedException ex) { Logger.getLogger(BotWrapper.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:c5db.control.ControlService.java
License:Apache License
private void startHttpRpc() { try {//from w w w . ja v a 2 s . c o m ServerBootstrap serverBootstrap = new ServerBootstrap(); ServerBootstrap serverBootstrap1 = serverBootstrap.group(acceptConnectionGroup, ioWorkerGroup) .channel(NioServerSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_BACKLOG, 100).childOption(ChannelOption.TCP_NODELAY, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // pipeline.addLast("logger", new LoggingHandler(LogLevel.DEBUG)); pipeline.addLast("http-server", new HttpServerCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(C5ServerConstants.MAX_CALL_SIZE)); pipeline.addLast("encode", new ServerHttpProtostuffEncoder()); pipeline.addLast("decode", new ServerHttpProtostuffDecoder()); pipeline.addLast("translate", new ServerDecodeCommandRequest()); pipeline.addLast("inc-messages", new MessageHandler()); } }); serverBootstrap.bind(modulePort).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // yay listenChannel = future.channel(); notifyStarted(); } else { LOG.error("Unable to bind to port {}", modulePort); notifyFailed(future.cause()); } } }); } catch (Exception e) { notifyFailed(e); } }
From source file:c5db.control.SimpleControlClient.java
License:Apache License
public ListenableFuture<CommandReply> sendRequest(CommandRpcRequest<?> request, InetSocketAddress remoteAddress) { SettableFuture<CommandReply> replyMessageFuture = SettableFuture.create(); ChannelFuture connectFuture = client.connect(remoteAddress); connectFuture.addListener(new ChannelFutureListener() { @Override/*from w w w .j av a2s . c o m*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().pipeline().addLast(new SimpleChannelInboundHandler<CommandReply>() { @Override protected void channelRead0(ChannelHandlerContext ctx, CommandReply msg) throws Exception { replyMessageFuture.set(msg); ctx.channel().close(); } }); // connected is fine, flush message: future.channel().writeAndFlush(request); } else { replyMessageFuture.setException(future.cause()); future.channel().close(); } } }); return replyMessageFuture; }
From source file:c5db.eventLogging.EventLogListener.java
License:Apache License
@Override protected void doStart() { nioEventLoopGroup.next().execute(() -> { Bootstrap bootstrap = new Bootstrap(); try {/*w w w .j a v a 2s.c o m*/ bootstrap.group(nioEventLoopGroup).channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true) .handler(new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(DatagramChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("protostuffDecoder", new UdpProtostuffDecoder<>(EventLogEntry.getSchema(), false)); p.addLast("logger", new MsgHandler()); } }); bootstrap.bind(port).addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) throws Exception { channel = future.channel(); } }); notifyStarted(); } catch (Throwable t) { notifyFailed(t); } }); }
From source file:c5db.eventLogging.EventLogService.java
License:Apache License
@Override protected void doStart() { nioEventLoopGroup.next().execute(() -> { Bootstrap bootstrap = new Bootstrap(); try {/*w w w . j a v a2s.c o m*/ bootstrap.group(nioEventLoopGroup).channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true) .handler(new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(DatagramChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("protostuffEncoder", new UdpProtostuffEncoder<>(EventLogEntry.getSchema(), false)); } }); bootstrap.bind(port).addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) throws Exception { broadcastChannel = future.channel(); } }); eventLogChannel.subscribe(fiber, msg -> { if (broadcastChannel == null) { LOG.debug("Broadcast channel isn't read yet, dropped message"); return; } LOG.trace("Sending event {}", msg); broadcastChannel .writeAndFlush(new UdpProtostuffEncoder.UdpProtostuffMessage<>(sendAddress, msg)); }); fiber.start(); notifyStarted(); } catch (Throwable t) { fiber.dispose(); notifyFailed(t); } }); }