io.netty.channel.socket.SocketChannel Java Examples

The following examples show how to use io.netty.channel.socket.SocketChannel. 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: Http2ServerChannelInitializer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Configure the pipeline for TLS NPN negotiation to HTTP/2.
 */
private void configureSSL(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    // 先通过 SSL/TLS 协商版本
    p.addLast(sslCtx.newHandler(ch.alloc()));
    // 根据版本加载不同的 ChannelHandler
    p.addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {
        @Override
        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                ctx.pipeline().addLast(bizGroup, "Http2ChannelHandler",
                    new Http2ChannelHandlerBuilder(serverHandler).build());
                return;
            }

            if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
                ctx.pipeline().addLast("HttpServerCodec", new HttpServerCodec());
                ctx.pipeline().addLast("HttpObjectAggregator", new HttpObjectAggregator(maxHttpContentLength));
                ctx.pipeline().addLast(bizGroup, "Http1ChannelHandler",
                    new Http1ServerChannelHandler(serverHandler));
                return;
            }

            throw new IllegalStateException("unknown protocol: " + protocol);
        }
    });
}
 
Example #2
Source File: EchoServer.java    From parker with MIT License 6 votes vote down vote up
public void start() throws Exception{
    NioEventLoopGroup group = new NioEventLoopGroup();
    ServerBootstrap strap = new ServerBootstrap();
    try {
        strap.group(group).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel sc) throws Exception{
                        sc.pipeline().addLast(new EchoServerHandler());
                    }
                });
        ChannelFuture future = strap.bind().sync();
        System.out.println(EchoServer.class.getName() + " started and listen on " + future.channel().localAddress());
        future.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
}
 
Example #3
Source File: AbstractHttpConnector.java    From minnal with Apache License 2.0 6 votes vote down vote up
public void initialize() {
	logger.info("Initializing the connector");
	
	EventLoopGroup bossGroup = new NioEventLoopGroup(configuration.getIoWorkerThreadCount());
    EventLoopGroup workerGroup = new NioEventLoopGroup(configuration.getIoWorkerThreadCount());
    bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup)
       .channel(NioServerSocketChannel.class)
       .option(ChannelOption.SO_BACKLOG, 100)
       .childOption(ChannelOption.TCP_NODELAY, true)
       .childHandler(new ChannelInitializer<SocketChannel>() {
           @Override
           public void initChannel(SocketChannel ch) throws Exception {
               ch.pipeline().addLast(new HttpRequestDecoder(), new HttpResponseEncoder(), new HttpObjectAggregator(configuration.getMaxContentLength()), AbstractHttpConnector.this);
               addChannelHandlers(ch.pipeline());
           }
       });
}
 
Example #4
Source File: NewNettyAcceptor.java    From cassandana with Apache License 2.0 6 votes vote down vote up
private void initializeWebSocketTransport(final NewNettyMQTTHandler handler, Config conf) {
    LOG.debug("Configuring Websocket MQTT transport");
    if(!conf.websocketEnabled) {
    	return;
    }
    
    int port = conf.websocketPort;// Integer.parseInt(webSocketPortProp);

    final MoquetteIdleTimeoutHandler timeoutHandler = new MoquetteIdleTimeoutHandler();

    String host = conf.websocketHost;
    initFactory(host, port, "Websocket MQTT", new PipelineInitializer() {

        @Override
        void init(SocketChannel channel) {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast(new HttpServerCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
            pipeline.addLast("webSocketHandler",
                    new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
            pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
            pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
            configureMQTTPipeline(pipeline, timeoutHandler, handler);
        }
    });
}
 
Example #5
Source File: HttpServerLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
    Bootstrap b = new Bootstrap();
    b.group(group)
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new HttpClientCodec());
                p.addLast(new HttpContentDecompressor());
                p.addLast(new SimpleChannelInboundHandler<HttpObject>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
                        response = prepareResponse(ctx, msg, response);
                    }
                });
            }
        });

    channel = b.connect(HOST, PORT)
        .sync()
        .channel();
}
 
Example #6
Source File: NettyIoAcceptor.java    From termd with Apache License 2.0 6 votes vote down vote up
public NettyIoAcceptor(NettyIoServiceFactory factory, final IoHandler handler) {
  this.factory = factory;
  this.handler = handler;
  channelGroup = new DefaultChannelGroup("sshd-acceptor-channels", GlobalEventExecutor.INSTANCE);
  bootstrap.group(factory.eventLoopGroup)
      .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 {
          ChannelPipeline p = ch.pipeline();
          p.addLast(new NettyIoSession(NettyIoAcceptor.this, handler).adapter);
        }
      });
}
 
Example #7
Source File: EchoServerV4.java    From netty.book.kor with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new EchoServerV4FirstHandler());
                p.addLast(new EchoServerV4SecondHandler());
            }
        });

        ChannelFuture f = b.bind(8888).sync();
        f.channel().closeFuture().sync();
    }
    finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
 
Example #8
Source File: HttpSnoopClientInitializer.java    From tools-journey with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();

    // Enable HTTPS if necessary.
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }

    p.addLast(new HttpClientCodec());

    // Remove the following line if you don't want automatic content decompression.
    p.addLast(new HttpContentDecompressor());

    // Uncomment the following line if you don't want to handle HttpContents.
    //p.addLast(new HttpObjectAggregator(1048576));

    p.addLast(new HttpSnoopClientHandler());
}
 
Example #9
Source File: NettyServer.java    From iot-dc3 with Apache License 2.0 6 votes vote down vote up
@SneakyThrows
public void start(int port) {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(group)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) {
                        socketChannel.pipeline().addLast(new WriteTimeoutHandler(30), new NettyServerHandler());
                    }
                });
        ChannelFuture future = bootstrap.bind().sync();
        future.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
}
 
Example #10
Source File: HttpUploadClientIntializer.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();

    if (sslCtx != null) {
        pipeline.addLast("ssl", sslCtx.newHandler(ch.alloc()));
    }

    pipeline.addLast("codec", new HttpClientCodec());

    // Remove the following line if you don't want automatic content decompression.
    pipeline.addLast("inflater", new HttpContentDecompressor());

    // to be used since huge file transfer
    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());

    pipeline.addLast("handler", new HttpUploadClientHandler());
}
 
Example #11
Source File: NettyChannelMap.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 6 votes vote down vote up
public  void remove(SocketChannel socketChannel){
    for (@SuppressWarnings("rawtypes") Map.Entry entry:map.entrySet()){
        if (entry.getValue()==socketChannel){
            log.info("#############客户端下线##############");
            log.info("下线主机名为:"+entry.getKey());
            Client client=clientService.selectClientByClientIP(entry.getKey().toString());
            if(client!=null)
            {
                client.setStatus(1);
                clientMapper.updateClient(client);
                //登陆失败,删除心跳map中的数据
                NettyServer.clientMap.remove(client.getClientIp());
            }
            map.remove(entry.getKey());
            socketChannel.close();
        }
    }
}
 
Example #12
Source File: NettyServerInitializer.java    From netty-learning-example with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline ph = ch.pipeline();

    //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式
    ph.addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS));
    // 解码和编码,应和客户端一致
    //传输的协议 Protobuf
    ph.addLast(new ProtobufVarint32FrameDecoder());
    ph.addLast(new ProtobufDecoder(UserMsg.User.getDefaultInstance()));
    ph.addLast(new ProtobufVarint32LengthFieldPrepender());
    ph.addLast(new ProtobufEncoder());

    //业务逻辑实现类
    ph.addLast("nettyServerHandler", new NettyServerHandler());
}
 
Example #13
Source File: BootstrapTemplate.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
public static void newServerBootstrap(String host, int port, ChannelInitializer<SocketChannel> initializer){
	EventLoopGroup bossGroup = new NioEventLoopGroup(1);
       EventLoopGroup workerGroup = new NioEventLoopGroup();
       try {
           ServerBootstrap b = new ServerBootstrap();
           b.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(initializer)
            .bind(port).sync().channel().closeFuture().sync();	        
       } catch (Exception e){   
       	e.printStackTrace();
       } 
       finally {
           bossGroup.shutdownGracefully();
           workerGroup.shutdownGracefully();
       }
}
 
Example #14
Source File: DefaultRedisKeeperServer.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
protected void startServer() throws InterruptedException {

      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup, workerGroup)
       .channel(NioServerSocketChannel.class)
       .handler(new LoggingHandler(LogLevel.INFO))
       .childHandler(new ChannelInitializer<SocketChannel>() {
           @Override
           public void initChannel(SocketChannel ch) throws Exception {
               ChannelPipeline p = ch.pipeline();
               p.addLast(new LoggingHandler(LogLevel.DEBUG));
               p.addLast(new NettySimpleMessageHandler());
               p.addLast(new NettyMasterHandler(DefaultRedisKeeperServer.this, new CommandHandlerManager(), keeperConfig.getTrafficReportIntervalMillis()));
           }
       });
      serverSocketChannel = (ServerSocketChannel) b.bind(currentKeeperMeta.getPort()).sync().channel();
  }
 
Example #15
Source File: NettyNetClient.java    From Lealone-Plugins with Apache License 2.0 6 votes vote down vote up
@Override
protected void createConnectionInternal(NetNode node, AsyncConnectionManager connectionManager,
        AsyncCallback<AsyncConnection> ac) {
    final InetSocketAddress inetSocketAddress = node.getInetSocketAddress();
    bootstrap.connect(node.getHost(), node.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                SocketChannel ch = (SocketChannel) future.channel();
                NettyWritableChannel writableChannel = new NettyWritableChannel(ch);
                AsyncConnection conn;
                if (connectionManager != null) {
                    conn = connectionManager.createConnection(writableChannel, false);
                } else {
                    conn = new TcpClientConnection(writableChannel, NettyNetClient.this);
                }
                ch.pipeline().addLast(new NettyNetClientHandler(NettyNetClient.this, connectionManager, conn));
                conn.setInetSocketAddress(inetSocketAddress);
                conn = NettyNetClient.this.addConnection(inetSocketAddress, conn);
                ac.setAsyncResult(conn);
            } else {
                ac.setAsyncResult(future.cause());
            }
        }
    });
}
 
Example #16
Source File: RpcNettyClientInitializer.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();

    if (sslCtx != null) {
        pipeline.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
    }
    pipeline.addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, new ByteBuf[]{
            Unpooled.wrappedBuffer(Constant.RPC_DELIMITER.getBytes())
    }));
    pipeline.addLast(DECODER);
    pipeline.addLast(ENCODER);
    // and then unit logic.
    pipeline.addLast(new RpcClientHandler(nodeId)/*CLIENT_HANDLER*/);
    pipeline.addLast(new RpcClientDecoder());
    pipeline.addLast(new StreamRpcClientHandler());
    pipeline.addLast(new RpcClientUnitHandler());
}
 
Example #17
Source File: Client.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void run() throws Exception {
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap(); // (2)
        b.group(workerGroup)
                .channel(NioSocketChannel.class) // (3)
                .handler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(clientHandler);

                    }
                })
                .option(ChannelOption.SO_KEEPALIVE, true); // (6)

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.connect("localhost", port).sync(); // (7)

        // 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();
    }
}
 
Example #18
Source File: WebSocketServerInitializer.java    From withme3.0 with MIT License 6 votes vote down vote up
@Override
    protected void initChannel(SocketChannel e) throws Exception {

        //protobuf处理器
//        e.pipeline().addLast("frameDecoder", new ProtobufVarint32FrameDecoder());//用于Decode前解决半包和粘包问题
        //此处需要传入自定义的protobuf的defaultInstance
        // e.pipeline().addLast("protobufDecoder",new ProtobufDecoder();
        //将请求和应答消息解码为http消息
        e.pipeline().addLast("http-codec", new HttpServerCodec());
        //HttpObjectAggregator:将Http消息的多个部分合成一条完整的消息
        e.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
        //ChunkedWriteHandler:向客户端发送HTML5文件
        e.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
        //在管道中添加我们自己实现的接收数据实现方法
        e.pipeline().addLast("handler", new WebSocketServerHandler());

    }
 
Example #19
Source File: CarbonServer.java    From disthene with MIT License 6 votes vote down vote up
public void run() throws InterruptedException {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new DelimiterBasedFrameDecoder(MAX_FRAME_LENGTH, false, Delimiters.lineDelimiter()));
                    p.addLast(new CarbonServerHandler(bus, configuration.getCarbon().getBaseRollup()));
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    logger.error(cause);
                    super.exceptionCaught(ctx, cause);
                }
            });

    // Start the server.
    b.bind(configuration.getCarbon().getBind(), configuration.getCarbon().getPort()).sync();
}
 
Example #20
Source File: NodeServerBootstrap.java    From GoPush with GNU General Public License v2.0 6 votes vote down vote up
@PostConstruct
public void start() throws Exception {

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workGroup)
            .channelFactory(NioServerSocketChannel::new)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    pipeline.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
                    pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                    pipeline.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8));
                    pipeline.addLast("idleStateHandler", new IdleStateHandler(300, 0, 0));
                    pipeline.addLast("handler", nodeChannelInBoundHandler);
                }
            })
            .option(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_SNDBUF, 2048)
            .option(ChannelOption.SO_RCVBUF, 1024);
    bootstrap.bind(goPushNodeServerConfig.getNodePort()).sync();
    log.info("Node server start successful! listening port: {}", goPushNodeServerConfig.getNodePort());
}
 
Example #21
Source File: NettyIoAcceptor.java    From termd with Apache License 2.0 6 votes vote down vote up
public NettyIoAcceptor(NettyIoServiceFactory factory, IoHandler handler) {
  this.factory = factory;
  this.handler = handler;
  channelGroup = new DefaultChannelGroup("sshd-acceptor-channels", GlobalEventExecutor.INSTANCE);;
  bootstrap.group(factory.eventLoopGroup)
      .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 {
          ChannelPipeline p = ch.pipeline();
          p.addLast(new NettyIoSession(NettyIoAcceptor.this, handler).adapter);
        }
      });
}
 
Example #22
Source File: HttpServerSPDY.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	String ip = "127.0.0.1";
	int port = 8080;
	// Configure SSL.
	SelfSignedCertificate ssc = new SelfSignedCertificate();
	final SslContext sslCtx = SslContext.newServerContext(
			ssc.certificate(), ssc.privateKey(), null, null,
			IdentityCipherSuiteFilter.INSTANCE,
			new ApplicationProtocolConfig(Protocol.ALPN,
					SelectorFailureBehavior.FATAL_ALERT,
					SelectedListenerFailureBehavior.FATAL_ALERT,
					SelectedProtocol.SPDY_3_1.protocolName(),
					SelectedProtocol.HTTP_1_1.protocolName()), 0, 0);

	ChannelInitializer<SocketChannel> channelInit = new ChannelInitializer<SocketChannel>() {
		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline p = ch.pipeline();
			p.addLast(sslCtx.newHandler(ch.alloc()));				
			p.addLast(new SpdyOrHttpHandler());
		}
	};
	NettyServerUtil.newHttpServerBootstrap(ip, port, channelInit);
}
 
Example #23
Source File: NettyClientServerCommunicationSystemClientSide.java    From protect with MIT License 6 votes vote down vote up
private ChannelInitializer getChannelInitializer() throws NoSuchAlgorithmException {

		Mac macDummy = Mac.getInstance(controller.getStaticConf().getHmacAlgorithm());

		final NettyClientPipelineFactory nettyClientPipelineFactory = new NettyClientPipelineFactory(this, sessionTable,
				macDummy.getMacLength(), controller, rl, signatureLength);

		ChannelInitializer channelInitializer = new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ch.pipeline().addLast(nettyClientPipelineFactory.getDecoder());
				ch.pipeline().addLast(nettyClientPipelineFactory.getEncoder());
				ch.pipeline().addLast(nettyClientPipelineFactory.getHandler());

			}
		};
		return channelInitializer;
	}
 
Example #24
Source File: GatewayServer.java    From pampas with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelInitializer<SocketChannel> newChannelInitializer() {

    return new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline()
                    .addLast(loggingHandler)
                    .addLast(new IdleStateHandler(30, 0, 10))
                    .addLast("decoder", new HttpRequestDecoder())
                    .addLast("http-aggregator", new HttpObjectAggregator(65536))
                    .addLast("encoder", new HttpResponseEncoder())
                    .addLast("chunk", new ChunkedWriteHandler())
                    .addLast(businessExecutors, "business-handler", new HttpServerHandler())
                    .addLast(new HeartbeatHandler())
                    .addLast(exceptionHandler);

        }
    };
}
 
Example #25
Source File: InitializerPipeline.java    From NettyFileTransfer with Apache License 2.0 5 votes vote down vote up
@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		//使用Netty实现的线程池
//        DefaultEventExecutorGroup e1=new DefaultEventExecutorGroup(16);
		ChannelPipeline pipeline = ch.pipeline();
//		pipeline.addLast("decoder", new MessageDecoder());
//      pipeline.addLast("encoder", new MessageEncoder());
//		pipeline.addLast(e1,"handler", new CommonHandler());
		ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
		ch.pipeline().addLast(new ObjectEncoder());
		pipeline.addLast("handler", new EchoServerHandler());
	}
 
Example #26
Source File: HttpMetricDataQueryServer.java    From blueflood with Apache License 2.0 5 votes vote down vote up
private void setupPipeline(SocketChannel channel, RouteMatcher router) {
    final ChannelPipeline pipeline = channel.pipeline();

    pipeline.addLast("logging", new LoggingHandler(LogLevel.TRACE)); //duplex handler
    pipeline.addLast("idleStateHandler", new IdleStateHandler(HTTP_CONNECTION_READ_IDLE_TIME_SECONDS, 0, 0)); //duplex handler
    pipeline.addLast("eventHandler", new UserDefinedEventHandler()); //duplex handler
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("decoder", new HttpRequestDecoder() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable thr) throws Exception {
            try {
                if (ctx.channel().isWritable()) {
                    log.debug("request decoder error " + thr.getCause() + " on channel " + ctx.channel().toString());
                    ctx.channel().write(
                            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST))
                                        .addListener(ChannelFutureListener.CLOSE);
                } else {
                    log.debug("channel " + ctx.channel().toString() + " is no longer writeable, not sending 400 response back to client");
                }
            } catch (Exception ex) {
                // If we are getting exception trying to write,
                // don't propagate to caller. It may cause this
                // method to be called again and will produce
                // stack overflow. So just log it here.
                log.debug("Can't write to channel " + ctx.channel().toString(), ex);
            }
        }
    });
    pipeline.addLast("chunkaggregator", new HttpObjectAggregator(httpMaxContentLength));
    pipeline.addLast("handler", new QueryStringDecoderAndRouter(router));
}
 
Example #27
Source File: Main.java    From riiablo with Apache License 2.0 5 votes vote down vote up
@Override
public void create() {
  Gdx.app.setLogLevel(Application.LOG_DEBUG);

  bossGroup = new NioEventLoopGroup();
  workerGroup = new NioEventLoopGroup();
  try {
    ServerBootstrap b = new ServerBootstrap()
        .group(bossGroup, workerGroup)
        .channel(NioServerSocketChannel.class)
        .childHandler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) {
            TcpEndpoint endpoint = new TcpEndpoint(ch, Main.this);
            Main.this.endpoint = endpoint;
            ch.pipeline()
                .addFirst(connectionLimiter)
                .addLast(new ChannelInboundHandlerAdapter() {
                  @Override
                  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    super.channelInactive(ctx);
                    notifyChannelInactive(ctx);
                  }
                })
                .addLast(new SizePrefixedDecoder())
                .addLast(new EndpointedChannelHandler<>(ByteBuf.class, endpoint))
                ;
          }
        })
        .option(ChannelOption.SO_BACKLOG, 128)
        .childOption(ChannelOption.TCP_NODELAY, true)
        .childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture f = b.bind(PORT).sync();
  } catch (Throwable t) {
    Gdx.app.error(TAG, t.getMessage(), t);
    Gdx.app.exit();
  }
}
 
Example #28
Source File: ServerChannelHandler.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    super.channelUnregistered(ctx);
    SocketChannel channel = (SocketChannel) ctx.channel();
    String nodeId = IpUtil.getNodeId(channel.remoteAddress());
    Attribute<Node> nodeAttribute = channel.attr(AttributeKey.valueOf("node-" + nodeId));

    Node node = nodeAttribute.get();
    if (node != null && node.getDisconnectListener() != null) {
        node.getDisconnectListener().action();
    }
    LoggerUtil.COMMON_LOG.info("Server Node is channelUnregistered:{}:{}", channel.remoteAddress().getHostString(), channel.remoteAddress().getPort());
}
 
Example #29
Source File: NettyServerUtil.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static void newHttpServerBootstrap(String ip, int port, SimpleChannelInboundHandler<? extends FullHttpRequest>  handler){	
	ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {			
		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline p = ch.pipeline();
			p.addLast("decoder", new HttpRequestDecoder());
			p.addLast("aggregator", new HttpObjectAggregator(65536));		
			p.addLast("encoder", new HttpResponseEncoder());
			p.addLast("chunkedWriter", new ChunkedWriteHandler());	
			p.addLast("handler", handler );
		}
	};
	newHttpServerBootstrap(ip, port, channelInitializer);
}
 
Example #30
Source File: ObjectEchoClient.java    From tools-journey 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) {
                        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();
    }
}