`
chenjunfei0617
  • 浏览: 5963 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

Netty Serial 3:分隔符解码器的应用

阅读更多
一:分隔符解码器简介
  在http://chenjunfei0617.iteye.com/blog/2244947中已经介绍了Netty自带的两种解码器,这一节为大家介绍一个Netty自带的一种分隔符解码器DelimiterBasedFrameDecoder。分隔符解码器顾名思义就是完成以分隔符作为结束标志的消息的解码。

二:分隔符解码器的应用
  本节以Echo服务为例,为大家介绍分隔符解码器的应用。

1、EchoServer
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * 分隔符解码器的实现
 * 
 * @author chenjf
 *
 */
public class EchoServer {
	public void bind(int port) {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 100)// .handler(new
															// LoggerHandler())
					.childHandler(new ChannelInitializer<SocketChannel>() {
						protected void initChannel(SocketChannel cp) throws Exception {
							ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
							cp.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
							cp.pipeline().addLast(new StringDecoder());
							cp.pipeline().addLast(new EchoServerHandler());
						};
					});
			ChannelFuture f = bootstrap.bind(port).sync();
			f.channel().closeFuture().sync();
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) {
		new EchoServer().bind(8080);
	}
}


2、EchoServerHandler
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class EchoServerHandler extends ChannelHandlerAdapter {

	private int count = 0;

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// TODO Auto-generated method stub
		String body = (String) msg;
		System.out.println("this is " + ++count + " times receive client :" + body);
		body += "$_";
		ByteBuf echo = Unpooled.copiedBuffer(body.getBytes());
		ctx.writeAndFlush(echo);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// TODO Auto-generated method stub
		cause.printStackTrace();
		ctx.close();
	}

}


3、EchoClient
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class EchoClient {
	public void connect(String host, int port) {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
					.handler(new ChannelInitializer<SocketChannel>() {
						protected void initChannel(SocketChannel s) throws Exception {
							ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
							s.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
							s.pipeline().addLast(new StringDecoder());
							s.pipeline().addLast(new EchoClienHandler());
						};
					});
			ChannelFuture f = bootstrap.connect(host, port).sync();

			f.channel().closeFuture().sync();
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			group.shutdownGracefully();
		}
	}

	public static void main(String[] args) {
		new EchoClient().connect("localhost", 8080);
	}
}


4、EchoClienHandler
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class EchoClienHandler extends ChannelHandlerAdapter {

	private int count = 0;

	public static final String req = "hello,welcome to netty.$_";

	public EchoClienHandler() {

	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		for (int i = 0; i < 10; i++) {
			ctx.writeAndFlush(Unpooled.copiedBuffer(req.getBytes()));
		}
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("this is " + ++count + " times receive server :" + msg);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// TODO Auto-generated method stub
		ctx.close();
	}
}


运行结果如下:
服务器端:
this is 1 times receive client :hello,welcome to netty.
this is 2 times receive client :hello,welcome to netty.
this is 3 times receive client :hello,welcome to netty.
this is 4 times receive client :hello,welcome to netty.
this is 5 times receive client :hello,welcome to netty.
this is 6 times receive client :hello,welcome to netty.
this is 7 times receive client :hello,welcome to netty.
this is 8 times receive client :hello,welcome to netty.
this is 9 times receive client :hello,welcome to netty.
this is 10 times receive client :hello,welcome to netty.

客户端:
this is 1 times receive server :hello,welcome to netty.
this is 2 times receive server :hello,welcome to netty.
this is 3 times receive server :hello,welcome to netty.
this is 4 times receive server :hello,welcome to netty.
this is 5 times receive server :hello,welcome to netty.
this is 6 times receive server :hello,welcome to netty.
this is 7 times receive server :hello,welcome to netty.
this is 8 times receive server :hello,welcome to netty.
this is 9 times receive server :hello,welcome to netty.
this is 10 times receive server :hello,welcome to netty.
分享到:
评论

相关推荐

    netty分隔符和定长解码器的应用

    本篇将深入探讨Netty中的两种解码器:分隔符解码器(DelimiterBasedFrameDecoder)和定长解码器(FixedLengthFrameDecoder)。 首先,我们来看分隔符解码器DelimiterBasedFrameDecoder。在许多网络协议中,消息通常...

    netty 分隔符解码器使用实例

    Netty框架中LineBasedFrameDecoder分隔符解码器解决考虑TCP的粘包与拆包问题。依次编译bytebuf中的可读字符,判断看是否有“\n”或者“\r\n”,如果有,就以此位置为结束位置,从可读索引到结束位置区间的字节就组成...

    netty-frameDecoder:换行符,自定义分隔符,定长度解码器

    netty-frameDecoder换行符,自定义分隔符,定长度解码器说明使用tcp传送数据,由于缓存区大小的设置,MSS的tcp分段等因素,数据传输时会出现TCP粘包/拆包的问题。但是底层的tcp无法理解上层的业务数据,所以在底层也...

    分隔符和定长解码器的应用

    本篇将详细探讨分隔符解码器(DelimiterBasedFrameDecoder)和定长解码器(FixedLengthFrameDecoder)在Netty中的应用,以及它们如何帮助我们高效地处理网络数据。 首先,让我们了解这两个解码器的基本概念: 1. ...

    netty-all-4.1.68.Final-API文档-中文版.zip

    赠送jar包:netty-all-4.1.68.Final.jar; 赠送原API文档:netty-all-4.1.68.Final-javadoc.jar; 赠送源代码:netty-all-4.1.68.Final-sources.jar; 赠送Maven依赖信息文件:netty-all-4.1.68.Final.pom; 包含...

    netty服务器通讯说明: 服务器条件NETTY框架编程: 服务器IP:192.168.2.106 端口8810

    netty服务器通讯说明: 服务器条件NETTY框架编程: 服务器IP:192.168.2.106 端口8810 数据传输的方式:从串口接收到一条完整的协议数据,计算出数据字节长度,打包成HtAlingProtocol类,并发送给服务器; package ...

    netty-all-4.1.5.Final完整pom.xml文件配置

    3. **强大的编码解码器**:Netty提供了一系列预定义的编解码器,如ByteBuf编码器和解码器,HTTP、WebSocket等协议的编解码器,使得处理各种协议变得更加容易。 4. **线程模型**:Netty采用EventLoopGroup和...

    netty-all-4.1.27.Final-API文档-中文版.zip

    赠送jar包:netty-all-4.1.27.Final.jar; 赠送原API文档:netty-all-4.1.27.Final-javadoc.jar; 赠送源代码:netty-all-4.1.27.Final-sources.jar; 赠送Maven依赖信息文件:netty-all-4.1.27.Final.pom; 包含...

    netty-common-4.1.65.Final-API文档-中英对照版.zip

    赠送jar包:netty-common-4.1.65.Final.jar; 赠送原API文档:netty-common-4.1.65.Final-javadoc.jar; 赠送源代码:netty-common-4.1.65.Final-sources.jar; 赠送Maven依赖信息文件:netty-common-4.1.65.Final....

    netty-common-4.1.68.Final-API文档-中文版.zip

    赠送jar包:netty-common-4.1.68.Final.jar; 赠送原API文档:netty-common-4.1.68.Final-javadoc.jar; 赠送源代码:netty-common-4.1.68.Final-sources.jar; 赠送Maven依赖信息文件:netty-common-4.1.68.Final....

    Netty+自定义Protobuf编解码器

    在分布式系统和网络通信中,Netty是一个非常流行的高性能、异步事件驱动的网络应用程序框架,用于快速开发可维护的高性能协议服务器和客户端。而Protocol Buffers(简称Protobuf)是Google开发的一种数据序列化协议...

    netty-transport-4.1.73.Final-API文档-中英对照版.zip

    赠送jar包:netty-transport-4.1.73.Final.jar; 赠送原API文档:netty-transport-4.1.73.Final-javadoc.jar; 赠送源代码:netty-transport-4.1.73.Final-sources.jar; 赠送Maven依赖信息文件:netty-transport-...

    Netty 入门与实战:仿写微信 IM 即时通讯系统.pdf

    5. **自定义编解码器**:用于转换自定义协议的数据格式。 6. **Pipeline与ChannelHandler**:用于组织业务逻辑处理器。 7. **定时心跳机制**:保持长连接的有效性,避免网络连接因长时间无活动而断开。 8. **连接...

    Netty进阶之路:跟着案例学Netty 完整版.pdf

    《Netty进阶之路:跟着案例学Netty》中的案例涵盖了Netty的启动和停止、内存、并发多线程、性能、可靠性、安全等方面,囊括了Netty绝大多数常用的功能及容易让人犯错的地方。在案例的分析过程中,还穿插讲解了Netty...

    netty-all-4.1.68.Final-API文档-中英对照版.zip

    赠送jar包:netty-all-4.1.68.Final.jar; 赠送原API文档:netty-all-4.1.68.Final-javadoc.jar; 赠送源代码:netty-all-4.1.68.Final-sources.jar; 赠送Maven依赖信息文件:netty-all-4.1.68.Final.pom; 包含...

    Netty 入门与实战:仿写微信 IM 即时通讯系统

    在本文中,我们将深入探讨Netty框架,并通过实战项目——仿写微信IM即时通讯系统,来深入了解其在高性能网络应用中的应用。Netty是Java领域中一个高效的异步事件驱动的网络应用程序框架,它为快速开发可维护的高性能...

    Netty入门与实战:仿写微信IM即时通讯系统

    5. **自定义编解码器**:实现自定义的编解码器,将业务数据编码成字节流或将字节流解码回业务数据。 6. **Pipeline与ChannelHandler的运用**:深入理解Netty的事件处理模型,合理配置处理链。 7. **心跳机制的设计**...

    netty-transport-4.1.27.Final-API文档-中英对照版.zip

    赠送jar包:netty-transport-4.1.27.Final.jar; 赠送原API文档:netty-transport-4.1.27.Final-javadoc.jar; 赠送源代码:netty-transport-4.1.27.Final-sources.jar; 赠送Maven依赖信息文件:netty-transport-...

    跟闪电侠学Netty:Netty即时聊天实战与底层原理-book-netty.zip

    《跟闪电侠学Netty:Netty即时聊天实战与底层原理》是一本深入浅出的Netty技术指南,旨在帮助读者掌握Netty框架,并利用它实现即时聊天应用,同时理解其底层工作原理。Netty是Java领域的一款高性能、异步事件驱动的...

    netty-resolver-4.1.65.Final-API文档-中文版.zip

    赠送jar包:netty-resolver-4.1.65.Final.jar; 赠送原API文档:netty-resolver-4.1.65.Final-javadoc.jar; 赠送源代码:netty-resolver-4.1.65.Final-sources.jar; 赠送Maven依赖信息文件:netty-resolver-4.1.65...

Global site tag (gtag.js) - Google Analytics