Java Code Examples for io.netty.handler.codec.string.StringDecoder

The following examples show how to use io.netty.handler.codec.string.StringDecoder. These examples are extracted from open source projects. 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 Project: netty-4.1.22   Source File: SecureChatServerInitializer.java    License: Apache License 2.0 7 votes vote down vote up
@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());
}
 
Example 2
Source Project: netty-learning   Source File: NettyClient.java    License: Apache License 2.0 7 votes vote down vote up
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();
    }
}
 
Example 3
Source Project: netty-4.1.22   Source File: Server.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 4
Source Project: julongchain   Source File: SecureChatServerInitializer.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 5
Source Project: julongchain   Source File: SecureChatClientInitializer.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 6
Source Project: java-study   Source File: NettyClientDemo5.java    License: Apache License 2.0 6 votes vote down vote up
/**
		 * 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();
	    }
 
Example 7
Source Project: java-study   Source File: NettyClientDemo2.java    License: Apache License 2.0 6 votes vote down vote up
/**
* 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();
  }
 
Example 8
Source Project: java-study   Source File: NettyClientDemo4.java    License: Apache License 2.0 6 votes vote down vote up
/**
* 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();
  }
 
Example 9
Source Project: netty-cookbook   Source File: Receiver.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 10
Source Project: GoPush   Source File: NodeServerBootstrap.java    License: 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 11
Source Project: x-pipe   Source File: SecureChatClientInitializer.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 12
Source Project: Jupiter   Source File: MonitorServer.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 13
Source Project: netty-cookbook   Source File: Receiver.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 14
Source Project: netty4.0.27Learn   Source File: RxtxClient.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 15
Source Project: dyno   Source File: EmbeddedRedisInitializer.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 16
Source Project: dubbo-2.6.5   Source File: QosProcessHandler.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 17
Source Project: spring-boot-demo   Source File: ServerChannelInitializer.java    License: MIT License 5 votes vote down vote up
@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());
}
 
Example 18
Source Project: ANetty   Source File: ANetty.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 构造
 * @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);
}
 
Example 19
/**
 * 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);
}
 
Example 20
Source Project: ext-opensource-netty   Source File: SimpleClient.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@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());
}
 
Example 21
/**
 * 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);
}
 
Example 22
@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();
    }
}
 
Example 23
Source Project: netty-learning-example   Source File: NettServer.java    License: Apache License 2.0 5 votes vote down vote up
@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!");
}
 
Example 24
Source Project: Netty_Demo   Source File: NettyClientInitializer.java    License: Apache License 2.0 5 votes vote down vote up
@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));
    }
 
Example 25
Source Project: java-tutorial   Source File: SimpleChatClientInitializer.java    License: MIT License 5 votes vote down vote up
@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());
}
 
Example 26
Source Project: java-study   Source File: NettyClientFilter.java    License: Apache License 2.0 5 votes vote down vote up
@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()); //客户端的逻辑
    }
 
Example 27
Source Project: java-study   Source File: NettyServerFilter.java    License: Apache License 2.0 5 votes vote down vote up
@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());// 服务端业务逻辑
     }
 
Example 28
Source Project: java-study   Source File: NettyServerDemo5.java    License: Apache License 2.0 5 votes vote down vote up
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();  
    }  
}
 
Example 29
Source Project: java-study   Source File: NettyServerDemo2.java    License: Apache License 2.0 5 votes vote down vote up
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,释放掉所有资源包括创建的线程
        }  
    }
 
Example 30
Source Project: java-study   Source File: NettyClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
* 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();  
   }