类 io.netty.handler.codec.string.StringDecoder 源码实例Demo

下面列出了怎么用 io.netty.handler.codec.string.StringDecoder 的API类实例代码及写法,或者点击链接到github查看源代码。


@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatServerHandler());
}
 
源代码2 项目: netty-4.1.22   文件: Server.java

public static void main(String[] args) throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workGroup = new NioEventLoopGroup();
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,100)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new StringEncoder());
                    pipeline.addLast(new StringDecoder());
                    pipeline.addLast(new ServerHandler());
                }
            });
    ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress("172.28.86.151",8080)).sync();
    channelFuture.channel().closeFuture().sync();
    bossGroup.shutdownGracefully();
    workGroup.shutdownGracefully();
}
 

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // 添加SSL用于加密每一个步骤.
    // 在本次演示中我们在服务端使用了一张虚拟的证书,可以接收任何有效的客户端证书.
    // 但在真实场景中你需要一个更复杂的客户端和服务端标记.
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));

    // SSL之上添加编解码处理.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // 处理业务逻辑.
    pipeline.addLast(new SecureChatServerHandler());
}
 

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // 添加SSL用于加密每一个步骤.
    // 在本次演示中我们在服务端使用了一张虚拟的证书,可以接收任何有效的客户端证书.
    // 但在真实场景中你需要一个更复杂的客户端和服务端标记.
    pipeline.addLast(sslCtx.newHandler(ch.alloc(), SecureChatClient.HOST, SecureChatClient.PORT));

    // SSL之上添加编解码处理.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // 处理业务逻辑.
    pipeline.addLast(new SecureChatClientHandler());
}
 
源代码5 项目: java-study   文件: NettyClientDemo5.java

/**
		 * Netty创建全部都是实现自AbstractBootstrap。
		 * 客户端的是Bootstrap,服务端的则是ServerBootstrap。
		 **/
	    public static void main(String[] args) throws InterruptedException, IOException { 
	        	 b.group(group)  
	             .channel(NioSocketChannel.class)  
	             .option(ChannelOption.TCP_NODELAY,true)  
	             .handler(new ChannelInitializer<SocketChannel>() {  
	                 @Override  
	                 public void initChannel(SocketChannel ch) throws Exception {  
	                     ChannelPipeline p = ch.pipeline();  
	                     //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式
	                     //因为服务端设置的超时时间是5秒,所以设置4秒
	                     p.addLast( new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS));  
	                     p.addLast( new StringDecoder());  
	                     p.addLast( new StringEncoder());  
	                     p.addLast(new NettyClientHandlerDemo5());   //绑定自定义业务 
	                 }  
	             });  
	            // 连接服务端
	            ch = b.connect(host, port).sync().channel();
	            System.out.println("客户端成功启动...");
	            //发送消息
//	            star();
	    }
 
源代码6 项目: java-study   文件: NettyClientDemo2.java

/**
* Netty创建全部都是实现自AbstractBootstrap。
* 客户端的是Bootstrap,服务端的则是ServerBootstrap。
**/
  public static void main(String[] args) throws InterruptedException, IOException { 
      	 b.group(group)  
           .channel(NioSocketChannel.class)  
           .option(ChannelOption.TCP_NODELAY,true)  
           .handler(new ChannelInitializer<SocketChannel>() {  
               @Override  
               public void initChannel(SocketChannel ch) throws Exception {  
                   ChannelPipeline p = ch.pipeline();  
                   p.addLast(new StringDecoder());    //绑定解码器
                   p.addLast(new NettyClientHandlerDemo2());   //绑定自定义业务 
               }  
           });  
          // 连接服务端
          ch = b.connect(host, port).sync().channel();
          System.out.println("客户端成功启动...");
   //       star();
  }
 
源代码7 项目: java-study   文件: NettyClientDemo4.java

/**
* Netty创建全部都是实现自AbstractBootstrap。
* 客户端的是Bootstrap,服务端的则是ServerBootstrap。
**/
  public static void main(String[] args) throws InterruptedException, IOException { 
      	 b.group(group)  
           .channel(NioSocketChannel.class)  
           .option(ChannelOption.TCP_NODELAY,true)  
           .handler(new ChannelInitializer<SocketChannel>() {  
               @Override  
               public void initChannel(SocketChannel ch) throws Exception {  
                   ChannelPipeline p = ch.pipeline();  
                   p.addLast(new StringDecoder());     //绑定自定义编码器
                   p.addLast(new NettyClientHandlerDemo4());   //绑定自定义业务 
               }  
           });  
          // 连接服务端
          ch = b.connect(host, port).sync().channel();
          System.out.println("客户端成功启动...");
          //发送消息
          star();
  }
 
源代码8 项目: netty-cookbook   文件: Receiver.java

public static void main(String[] args) throws Exception {
	ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
		@Override
		public void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline p = ch.pipeline();
			p.addLast(new StringEncoder());
			p.addLast(new StringDecoder());
			p.addLast(new ChannelInboundHandlerAdapter() {
				@Override
				public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
					System.out.println(msg);
					ctx.close();
				}
			});
		}
	};
	BootstrapTemplate.newServerBootstrap(HOST, PORT, initializer);
}
 
源代码9 项目: GoPush   文件: NodeServerBootstrap.java

@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());
}
 
源代码10 项目: netty-learning   文件: NettyClient.java

public void connect(String host, int port) throws InterruptedException {
    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
                    protected void initChannel(SocketChannel ch) throws Exception {

                        ch.pipeline().addLast(new FixedLengthFrameDecoder(1<<5));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new StringEncoder());

                        ch.pipeline().addLast(new ClientHandler());
                    }
                });

        ChannelFuture future = b.connect(host, port).sync();

        future.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(createSslHandler(getClientSSLContext()));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatClientHandler());
}
 
源代码12 项目: Jupiter   文件: MonitorServer.java

@Override
public ChannelFuture bind(SocketAddress localAddress) {
    ServerBootstrap boot = bootstrap();

    initChannelFactory();

    boot.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(
                    new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()),
                    new StringDecoder(StandardCharsets.UTF_8),
                    encoder,
                    handler);
        }
    });

    setOptions();

    return boot.bind(localAddress);
}
 
源代码13 项目: netty-cookbook   文件: Receiver.java

public static void main(String[] args) throws Exception {
	ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
		@Override
		public void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline p = ch.pipeline();
			p.addLast(new StringEncoder());
			p.addLast(new StringDecoder());
			p.addLast(new ChannelInboundHandlerAdapter() {
				@Override
				public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
					System.out.println(msg);
					ctx.close();
				}
			});
		}
	};
	BootstrapTemplate.newServerBootstrap(HOST, PORT, initializer);
}
 
源代码14 项目: netty4.0.27Learn   文件: RxtxClient.java

public static void main(String[] args) throws Exception {
    EventLoopGroup group = new OioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(RxtxChannel.class)
         .handler(new ChannelInitializer<RxtxChannel>() {
             @Override
             public void initChannel(RxtxChannel ch) throws Exception {
                 ch.pipeline().addLast(
                     new LineBasedFrameDecoder(32768),
                     new StringEncoder(),
                     new StringDecoder(),
                     new RxtxClientHandler()
                 );
             }
         });

        ChannelFuture f = b.connect(new RxtxDeviceAddress(PORT)).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
源代码15 项目: dyno   文件: EmbeddedRedisInitializer.java

@Override
protected void initChannel(final SocketChannel ch) throws Exception {
    final ChannelPipeline pipeline = ch.pipeline();

    if (useSsl) {
        final SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.getNeedClientAuth();

        pipeline.addLast("sslHandler", new SslHandler(sslEngine));
    }


    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    pipeline.addLast(new MockedResponseHandler(response));
}
 
源代码16 项目: dubbo-2.6.5   文件: QosProcessHandler.java

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 1) {
        return;
    }

    // read one byte to guess protocol
    final int magic = in.getByte(in.readerIndex());

    ChannelPipeline p = ctx.pipeline();
    p.addLast(new LocalHostPermitHandler(acceptForeignIp));
    if (isHttp(magic)) {
        // no welcome output for http protocol
        if (welcomeFuture != null && welcomeFuture.isCancellable()) {
            welcomeFuture.cancel(false);
        }
        p.addLast(new HttpServerCodec());
        p.addLast(new HttpObjectAggregator(1048576));
        p.addLast(new HttpProcessHandler());
        p.remove(this);
    } else {
        p.addLast(new LineBasedFrameDecoder(2048));
        p.addLast(new StringDecoder(CharsetUtil.UTF_8));
        p.addLast(new StringEncoder(CharsetUtil.UTF_8));
        p.addLast(new IdleStateHandler(0, 0, 5 * 60));
        p.addLast(new TelnetProcessHandler());
        p.remove(this);
    }
}
 

@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    //添加编解码
    socketChannel.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
    socketChannel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
    socketChannel.pipeline().addLast(new NettyServerHandler());
}
 
源代码18 项目: ANetty   文件: ANetty.java

/**
 * 构造
 * @param onChannelHandler {@link OnChannelHandler}
 * @param isDebug
 */
public ANetty(final OnChannelHandler onChannelHandler, boolean isDebug){
    this.isDebug = isDebug;
    this.mChannelInitializer = new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch){
            //建立管道
            ChannelPipeline channelPipeline = ch.pipeline();
            //添加相关编码器,解码器,处理器等
            channelPipeline
                    .addLast(new StringEncoder())
                    .addLast(new StringDecoder())
                    .addLast(new StringChannelHandler(){
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                            super.channelRead0(ctx, msg);
                            if(isDebug){
                                Log.d(TAG,"Received message:" + msg);
                            }
                            if(onChannelHandler!=null){
                                mMainHandler.post(() -> onChannelHandler.onMessageReceived(ctx,msg));
                            }
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            super.exceptionCaught(ctx, cause);
                            if(isDebug){
                                Log.w(TAG,cause.getMessage());
                            }
                            if(onChannelHandler!=null){
                                mMainHandler.post(() -> onChannelHandler.onExceptionCaught(ctx,cause));
                            }
                        }
                    });
        }
    };
    initHandlerThread();
    mHandler.sendEmptyMessage(NETTY_INIT);
}
 
源代码19 项目: jumbune   文件: JumbuneAgentDecoder.java

/**
 * Invoke log files receive handler.
 *
 * @param ctx the ctx
 */
private void invokeLogFilesReceiveHandler(ChannelHandlerContext ctx) {
	ChannelPipeline p = ctx.pipeline();
	
	p.addLast("stringDecoder", new StringDecoder());
	p.addLast("delegator", new Delegator(receiveDirectory));
	p.addLast("stringEncoder", new StringEncoder());
	p.addLast("logStreamer", new LogFilesEncoder());
	p.remove(this);
}
 
源代码20 项目: ext-opensource-netty   文件: SimpleClient.java

@Override
protected void initSocketChannel(SocketChannel ch) {
	super.initSocketChannel(ch);
	ch.pipeline().addLast(new LineBasedFrameDecoder(1024)); 
	ch.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));
	ch.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8")));
	///ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Delimiters.lineDelimiter()));

	ch.pipeline().addLast(new LogDispatchHandler());
	ch.pipeline().addLast(new ClientSimpleHandler());
	///ch.pipeline().addLast(new ClientSimpleHandlerX());
}
 
源代码21 项目: jumbune   文件: JumbuneAgentDecoder.java

/**
 * Invoke log files receive handler.
 *
 * @param ctx the ctx
 */
private void invokeLogFilesReceiveHandlerForHA(ChannelHandlerContext ctx) {
	ChannelPipeline p = ctx.pipeline();		
	EventExecutor e1 = new DefaultEventExecutorGroup(1).next();
	p.addLast("stringDecoder", new StringDecoder());
	p.addLast("delegator", new Delegator(receiveDirectory));
	p.addLast(HEARTBEAT_HANDLER, new HeartbeatHandler(JumbuneAgent.getHeartBeatMillis(), 
			JumbuneAgent.getHeartBeatMillis(), JumbuneAgent.getHeartBeatMillis()));
	p.addLast("stringEncoder", new StringEncoder());
	p.addLast(e1, new LogFilesEncoder());
	p.remove(this);
}
 

@Override
public void run() {
    final Bootstrap boot = new Bootstrap();
    final ThreadFactory clientFactory = new DefaultThreadFactory("client");
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1,
            clientFactory, NioUdtProvider.BYTE_PROVIDER);
    try {
        boot.group(connectGroup)
                .channelFactory(NioUdtProvider.BYTE_CONNECTOR)
                .handler(new ChannelInitializer<UdtChannel>() {

                    @Override
                    protected void initChannel(final UdtChannel ch)
                            throws Exception {
                        final ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("framer",
                                new DelimiterBasedFrameDecoder(8192,
                                        Delimiters.lineDelimiter()));
                        pipeline.addLast("decoder", new StringDecoder(
                                CharsetUtil.UTF_8));
                        pipeline.addLast("encoder", new StringEncoder(
                                CharsetUtil.UTF_8));
                        pipeline.addLast("handler", new ClientHandler());
                    }
                });
        channel = boot.connect(address).sync().channel();
        isRunning = true;
        log.info("Client ready.");
        waitForRunning(false);
        log.info("Client closing...");
        channel.close().sync();
        isShutdown = true;
        log.info("Client is done.");
    } catch (final Throwable e) {
        log.error("Client failed.", e);
    } finally {
        connectGroup.shutdownGracefully().syncUninterruptibly();
    }
}
 
源代码23 项目: netty-learning-example   文件: NettServer.java

@PostConstruct
public void init() throws Exception {

    log.info("Starting Netty Server");
    bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
    workerGroup = new NioEventLoopGroup(workerGroupThreadCount);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                    pipeline.addLast("decoder", new StringDecoder());
                    pipeline.addLast("encoder", new StringEncoder());
                    NettyServerHandler nettyServerHandler = new NettyServerHandler(deviceService);
                    pipeline.addLast(nettyServerHandler);
                }
            });

    serverChannel = b.bind(host, port).sync().channel();


    log.info("Netty Server started!");
}
 
源代码24 项目: Netty_Demo   文件: NettyClientInitializer.java

@Override
    protected void initChannel(SocketChannel ch) throws Exception {
//        SslContext sslCtx = SSLContext.getDefault()
//                .createSSLEngine(InsecureTrustManagerFactory.INSTANCE).build();

        ChannelPipeline pipeline = ch.pipeline();
//        pipeline.addLast(sslCtx.newHandler(ch.alloc()));    // 开启SSL
        pipeline.addLast(new LoggingHandler(LogLevel.INFO));    // 开启日志,可以设置日志等级
        pipeline.addLast("IdleStateHandler", new IdleStateHandler(6, 0, 0));
        pipeline.addLast("StringDecoder", new StringDecoder());//解码器 这里要与服务器保持一致
        pipeline.addLast("StringEncoder", new StringEncoder());//编码器 这里要与服务器保持一致
        pipeline.addLast(new NettyClientHandler(listener));
    }
 

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());
    pipeline.addLast("handler", new SimpleChatClientHandler());
}
 
源代码26 项目: java-study   文件: NettyClientFilter.java

@Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline ph = ch.pipeline();
        /*
         * 解码和编码,应和服务端一致
         * */
//        ph.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        ph.addLast("decoder", new StringDecoder());
        ph.addLast("encoder", new StringEncoder());
        ph.addLast("handler", new NettyClientHandler()); //客户端的逻辑
    }
 
源代码27 项目: java-study   文件: NettyServerFilter.java

@Override
     protected void initChannel(SocketChannel ch) throws Exception {
         ChannelPipeline ph = ch.pipeline();
         // 以("\n")为结尾分割的 解码器
//        ph.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
         // 解码和编码,应和客户端一致
         ph.addLast("decoder", new StringDecoder());
         ph.addLast("encoder", new StringEncoder());
         ph.addLast("handler", new NettyServerHandler());// 服务端业务逻辑
     }
 
源代码28 项目: java-study   文件: NettyServerDemo5.java

public void start(){  
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);  
    EventLoopGroup workerGroup = new NioEventLoopGroup();  
    try {  
        ServerBootstrap sbs = new ServerBootstrap().group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port))  
                .childHandler(new ChannelInitializer<SocketChannel>() {  
                      
                    protected void initChannel(SocketChannel ch) throws Exception { 
                    	 ChannelPipeline p = ch.pipeline(); 
                    	 //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式
                    	 p.addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS));
                    	 p.addLast(new StringDecoder());  			//String解码器
                    	 p.addLast(new StringEncoder());  			//String编码器
                    	 p.addLast(new NettyServerHandlerDemo5());  //绑定自定义业务逻辑
                    };  
                      
                }).option(ChannelOption.SO_BACKLOG, 128)     
                .childOption(ChannelOption.SO_KEEPALIVE, true);  
         // 绑定端口,开始接收进来的连接  
         ChannelFuture future = sbs.bind(port).sync();    
           
         System.out.println("Netty服务端启动成功,端口为: " + port );  
         future.channel().closeFuture().sync();   //释放监听
    } catch (Exception e) {  
        bossGroup.shutdownGracefully();    //释放资源
        workerGroup.shutdownGracefully();  
    }  
}
 
源代码29 项目: java-study   文件: NettyServerDemo2.java

public void start(){  
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);  
        EventLoopGroup workerGroup = new NioEventLoopGroup();  
        try {  
            ServerBootstrap sbs = new ServerBootstrap().group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port))  
                    .childHandler(new ChannelInitializer<SocketChannel>() {  
                        protected void initChannel(SocketChannel ch) throws Exception { 
                        	ChannelPipeline p = ch.pipeline(); 
                         
                          p.addLast(new LineBasedFrameDecoder(2048));		//字节解码器 ,其中2048是规定一行数据最大的字节数。  用于解决拆包问题
//                          p.addLast(new FixedLengthFrameDecoder(100));   //定长数据帧的解码器 ,每帧数据100个字节就切分一次。  用于解决粘包问题        
//                          p.addLast(new DelimiterBasedFrameDecoder(1024,Unpooled.copiedBuffer("~_~".getBytes()))); //固定字符切分解码器 ,会以"~_~"为分隔符。  注意此方法要放到StringDecoder()上面
                            p.addLast(new StringDecoder());     //设置解码器
                            p.addLast(new NettyServerHandlerDemo2());   //绑定自定义事物
                        };  
                          
                    }).option(ChannelOption.SO_BACKLOG, 128)     
                    .childOption(ChannelOption.SO_KEEPALIVE, true);  
             // 绑定端口,开始接收进来的连接  
             ChannelFuture future = sbs.bind(port).sync();    
               
             System.out.println("服务端启动成功,端口为 :" + port );  
             future.channel().closeFuture().sync();  
        } catch (Exception e) {  
            bossGroup.shutdownGracefully();  //关闭EventLoopGroup,释放掉所有资源包括创建的线程
            workerGroup.shutdownGracefully();  //关闭EventLoopGroup,释放掉所有资源包括创建的线程
        }  
    }
 
源代码30 项目: java-study   文件: NettyClient.java

/**
* Netty创建全部都是实现自AbstractBootstrap。
* 客户端的是Bootstrap,服务端的则是	ServerBootstrap。
**/
public static void main(String[] args) throws Exception {  
try{ 
     b.group(group)  
      .channel(NioSocketChannel.class)  
      .option(ChannelOption.TCP_NODELAY, true)  
      .handler(new ChannelInitializer<SocketChannel>() {  
          @Override  
          public void initChannel(SocketChannel ch) throws Exception {  
              ChannelPipeline p = ch.pipeline();  
              p.addLast("decoder", new StringDecoder());
                    p.addLast("encoder", new StringEncoder());  
              p.addLast(new BaseClient1Handler());  
              p.addLast(new BaseClient2Handler());  
          }  
      });  
     
        ChannelFuture future = b.connect(host, port).sync();  // 连接服务端
     	 System.out.println("客户端连接成功!");  
        future.channel().writeAndFlush("Hello Netty Server ,I am a common client");//发送消息  
        future.channel().closeFuture().sync();   //关闭
	 } finally {  
	     group.shutdownGracefully();   //释放资源
	 }  
       
      // 	start();  
   }
 
 类所在包
 类方法
 同包方法