標籤:mina netty twisted 網路 非同步
在上一篇博文中,有介紹到用分行符號分割訊息的方法。但是這種方法有個小問題,如果訊息中本身就包含分行符號,那將會將這條訊息分割成兩條,結果就不對了。
本文介紹另外一種訊息分割方式,即上一篇博文中講的第2條:use a fixed length header that indicates the length of the body,用一個固定位元組數的Header首碼來指定Body的位元組數,以此來分割訊息。
上面圖中Header固定為4位元組,Header中儲存的是一個4位元組(32位)的整數,例如12即為0x0000000C,這個整數用來指定Body的長度(位元組數)。當讀完這麼多位元組的Body之後,又是下一條訊息的Header。
下面分別用MINA、Netty、Twisted來實現對這種訊息的切合和解碼。
MINA:
MINA提供了PrefixedStringCodecFactory來對這種類型的訊息進行編碼解碼,PrefixedStringCodecFactory預設Header的大小是4位元組,當然也可以指定成1或2。
public class TcpServer {public static void main(String[] args) throws IOException {IoAcceptor acceptor = new NioSocketAcceptor();// 4位元組的Header指定Body的位元組數,對這種訊息的處理acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new PrefixedStringCodecFactory(Charset.forName("UTF-8"))));acceptor.setHandler(new TcpServerHandle());acceptor.bind(new InetSocketAddress(8080));}}class TcpServerHandle extends IoHandlerAdapter {@Overridepublic void exceptionCaught(IoSession session, Throwable cause)throws Exception {cause.printStackTrace();}// 接收到新的資料@Overridepublic void messageReceived(IoSession session, Object message)throws Exception {String msg = (String) message;System.out.println("messageReceived:" + msg);}@Overridepublic void sessionCreated(IoSession session) throws Exception {System.out.println("sessionCreated");}@Overridepublic void sessionClosed(IoSession session) throws Exception {System.out.println("sessionClosed");}}
Netty:
Netty使用LengthFieldBasedFrameDecoder來處理這種訊息。下面代碼中的new LengthFieldBasedFrameDecoder(80, 0, 4, 0, 4)中包含5個參數,分別是int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip。maxFrameLength為訊息的最大長度,lengthFieldOffset為Header的位置,lengthFieldLength為Header的長度,lengthAdjustment為長度調整(預設Header中的值表示Body的長度,並不包含Header自己),initialBytesToStrip為去掉位元組數(預設解碼後返回Header+Body的全部內容,這裡設為4表示去掉4位元組的Header,只留下Body)。
public class TcpServer {public static void main(String[] args) throws InterruptedException {EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overridepublic void initChannel(SocketChannel ch)throws Exception {ChannelPipeline pipeline = ch.pipeline();// LengthFieldBasedFrameDecoder按行分割訊息,取出bodypipeline.addLast(new LengthFieldBasedFrameDecoder(80, 0, 4, 0, 4));// 再按UTF-8編碼轉成字串pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));pipeline.addLast(new TcpServerHandler());}});ChannelFuture f = b.bind(8080).sync();f.channel().closeFuture().sync();} finally {workerGroup.shutdownGracefully();bossGroup.shutdownGracefully();}}}class TcpServerHandler extends ChannelInboundHandlerAdapter {// 接收到新的資料@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {String message = (String) msg;System.out.println("channelRead:" + message);}@Overridepublic void channelActive(ChannelHandlerContext ctx) {System.out.println("channelActive");}@Overridepublic void channelInactive(ChannelHandlerContext ctx) {System.out.println("channelInactive");}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {cause.printStackTrace();ctx.close();}}
Twisted:
在Twisted中需要繼承Int32StringReceiver,不再繼承Protocol。Int32StringReceiver表示固定32位(4位元組)的Header,另外還有Int32StringReceiver、Int8StringReceiver等。而需要實現的接受資料事件的方法不再是dataReceived,也不是lineReceived,而是stringReceived。
# -*- coding:utf-8 –*-from twisted.protocols.basic import Int32StringReceiverfrom twisted.internet.protocol import Factoryfrom twisted.internet import reactorclass TcpServerHandle(Int32StringReceiver): # 新的串連建立 def connectionMade(self): print ‘connectionMade‘ # 串連斷開 def connectionLost(self, reason): print ‘connectionLost‘ # 接收到新的資料 def stringReceived(self, data): print ‘stringReceived:‘ + datafactory = Factory()factory.protocol = TcpServerHandlereactor.listenTCP(8080, factory)reactor.run()
下面是Java編寫的一個用戶端測試程式:
public class TcpClient {public static void main(String[] args) throws IOException {Socket socket = null;DataOutputStream out = null;try {socket = new Socket("localhost", 8080);out = new DataOutputStream(socket.getOutputStream());// 請求伺服器String data1 = "牛頓";byte[] outputBytes1 = data1.getBytes("UTF-8");out.writeInt(outputBytes1.length); // write headerout.write(outputBytes1); // write bodyString data2 = "愛因斯坦";byte[] outputBytes2 = data2.getBytes("UTF-8");out.writeInt(outputBytes2.length); // write headerout.write(outputBytes2); // write body} finally {// 關閉串連out.close();socket.close();}}}
MINA伺服器輸出結果:
sessionCreated
messageReceived:牛頓
messageReceived:愛因斯坦
sessionClosed
Netty伺服器輸出結果:
channelActive
channelRead:牛頓
channelRead:愛因斯坦
channelInactive
Twisted伺服器輸出結果:
connectionMade
stringReceived:牛頓
stringReceived:愛因斯坦
connectionLost
叉叉哥 轉載請註明出處:http://blog.csdn.net/xiao__gui/article/details/38752105