Mina、Netty、Twisted一起學(五):整合protobuf,nettyprotobuf

來源:互聯網
上載者:User

Mina、Netty、Twisted一起學(五):整合protobuf,nettyprotobuf

protobuf是Google的Protocol Buffers的簡稱,用於結構化資料和位元組碼之間互相轉換(序列化、還原序列化),一般應用於網路傳輸,可支援多種程式設計語言。

protobuf如何使用這裡不再介紹,本文主要介紹在MINA、Netty、Twisted中如何使用protobuf,不瞭解protobuf的同學可以去參考我的另一篇博文。

在前面的一篇博文中,有介紹到一種用一個固定為4位元組的首碼Header來指定Body的位元組數的一種訊息分割方式,在這裡同樣要使用到。只是其中Body的內容不再是字串,而是protobuf位元組碼。


在處理商務邏輯時,肯定不希望還要對資料進行序列化和還原序列化,而是希望直接操作一個對象,那麼就需要有相應的編碼器和解碼器,將序列化和還原序列化的邏輯寫在編碼器和解碼器中。有關編碼器和解碼器的實現,上一篇博文中有介紹。

Netty包中已經內建針對protobuf的編碼器和解碼器,那麼就不用再自己去實現了。而MINA、Twisted還需要自己去實現protobuf的編碼器和解碼器。

這裡定義一個protobuf資料結構,用於描述一個學生的資訊,儲存為StudentMsg.proto檔案:

message Student {    // ID    required int32 id = 1;      // 姓名    required string name = 2;    // email    optional string email = 3;    // 朋友    repeated string friends = 4;}

用StudentMsg.proto分別產生Java和Python代碼,將代碼加入到相應的項目中。產生的程式碼就不再貼上來了。

下面分別介紹在Netty、MINA、Twisted如何使用protobuf來傳輸Student資訊。

Netty:

Netty內建protobuf的編碼器和解碼器,分別是ProtobufEncoder和ProtobufDecoder。需要注意的是,ProtobufEncoder和ProtobufDecoder只負責protobuf的序列化和還原序列化,而處理訊息Header首碼和訊息分割的還需要LengthFieldBasedFrameDecoder和LengthFieldPrepender。LengthFieldBasedFrameDecoder即用於解析訊息Header首碼,根據Header中指定的Body位元組數截取Body,LengthFieldPrepender用於在wirte訊息時在訊息前面添加一個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>() {                        @Override                        public void initChannel(SocketChannel ch)                                throws Exception {                            ChannelPipeline pipeline = ch.pipeline();  // 負責通過4位元組Header指定的Body長度將訊息切割pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));// 負責將frameDecoder處理後的完整的一條訊息的protobuf位元組碼轉成Student對象pipeline.addLast("protobufDecoder",new ProtobufDecoder(StudentMsg.Student.getDefaultInstance()));// 負責將寫入的位元組碼加上4位元組Header首碼來指定Body長度pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));// 負責將Student對象轉成protobuf位元組碼pipeline.addLast("protobufEncoder", new ProtobufEncoder());                            pipeline.addLast(new TcpServerHandler());                        }                    });            ChannelFuture f = b.bind(8080).sync();            f.channel().closeFuture().sync();        } finally {            workerGroup.shutdownGracefully();            bossGroup.shutdownGracefully();        }    }}

處理事件時,接收和發送的參數直接就是Student對象:

public class TcpServerHandler extends ChannelInboundHandlerAdapter {    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) {            // 讀取用戶端傳過來的Student對象    StudentMsg.Student student = (StudentMsg.Student) msg;        System.out.println("ID:" + student.getId());        System.out.println("Name:" + student.getName());        System.out.println("Email:" + student.getEmail());        System.out.println("Friends:");        List<String> friends = student.getFriendsList();        for(String friend : friends) {        System.out.println(friend);        }        // 建立一個Student對象傳到用戶端        StudentMsg.Student.Builder builder = StudentMsg.Student.newBuilder();        builder.setId(9);        builder.setName("伺服器");        builder.setEmail("123@abc.com");        builder.addFriends("X");        builder.addFriends("Y");        StudentMsg.Student student2 = builder.build();        ctx.writeAndFlush(student2);    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {        cause.printStackTrace();        ctx.close();    }}

MINA:

在MINA中沒有針對protobuf的編碼器和解碼器,但是可以自己實現一個功能和Netty一樣的編碼器和解碼器。

編碼器:

public class MinaProtobufEncoder extends ProtocolEncoderAdapter {    @Override    public void encode(IoSession session, Object message,            ProtocolEncoderOutput out) throws Exception {    StudentMsg.Student student = (StudentMsg.Student) message;        byte[] bytes = student.toByteArray(); // Student對象轉為protobuf位元組碼        int length = bytes.length;                IoBuffer buffer = IoBuffer.allocate(length + 4);        buffer.putInt(length); // write header        buffer.put(bytes); // write body        buffer.flip();        out.write(buffer);    }}

解碼器:

public class MinaProtobufDecoder extends CumulativeProtocolDecoder {@Overrideprotected boolean doDecode(IoSession session, IoBuffer in,ProtocolDecoderOutput out) throws Exception {// 如果沒有接收完Header部分(4位元組),直接返回falseif (in.remaining() < 4) {return false;} else {// 標記開始位置,如果一條訊息沒傳輸完成則返回到這個位置in.mark();// 讀取header部分,擷取body長度int bodyLength = in.getInt();// 如果body沒有接收完整,直接返回falseif (in.remaining() < bodyLength) {in.reset(); // IoBuffer position回到原來標記的地方return false;} else {byte[] bodyBytes = new byte[bodyLength];in.get(bodyBytes); // 讀取body部分StudentMsg.Student student = StudentMsg.Student.parseFrom(bodyBytes); // 將body中protobuf位元組碼轉成Student對象out.write(student); // 解析出一條訊息return true;}}}}

MINA伺服器加入protobuf的編碼器和解碼器:

public class TcpServer {    public static void main(String[] args) throws IOException {        IoAcceptor acceptor = new NioSocketAcceptor();        // 指定protobuf的編碼器和解碼器        acceptor.getFilterChain().addLast("codec",                new ProtocolCodecFilter(new MinaProtobufEncoder(), new MinaProtobufDecoder()));        acceptor.setHandler(new TcpServerHandle());        acceptor.bind(new InetSocketAddress(8080));    }}

這樣,在處理商務邏輯時,就和Netty一樣了:

public class TcpServerHandle extends IoHandlerAdapter {    @Override    public void exceptionCaught(IoSession session, Throwable cause)            throws Exception {        cause.printStackTrace();    }        @Override    public void messageReceived(IoSession session, Object message)            throws Exception {    // 讀取用戶端傳過來的Student對象    StudentMsg.Student student = (StudentMsg.Student) message;        System.out.println("ID:" + student.getId());        System.out.println("Name:" + student.getName());        System.out.println("Email:" + student.getEmail());        System.out.println("Friends:");        List<String> friends = student.getFriendsList();        for(String friend : friends) {        System.out.println(friend);        }        // 建立一個Student對象傳到用戶端        StudentMsg.Student.Builder builder = StudentMsg.Student.newBuilder();        builder.setId(9);        builder.setName("伺服器");        builder.setEmail("123@abc.com");        builder.addFriends("X");        builder.addFriends("Y");        StudentMsg.Student student2 = builder.build();        session.write(student2);    }}

Twisted:

在Twisted中,首先定義一個ProtobufProtocol類,繼承Protocol類,充當編碼器和解碼器。處理商務邏輯的TcpServerHandle類再繼承ProtobufProtocol類,調用或重寫ProtobufProtocol提供的方法。

# -*- coding:utf-8 –*-from struct import pack, unpackfrom twisted.internet.protocol import Factoryfrom twisted.internet.protocol import Protocolfrom twisted.internet import reactorimport StudentMsg_pb2# protobuf編碼、解碼器class ProtobufProtocol(Protocol):    # 用於暫時存放接收到的資料    _buffer = b""    def dataReceived(self, data):        # 上次未處理的資料加上本次接收到的資料        self._buffer = self._buffer + data        # 一直迴圈直到新的訊息沒有接收完整        while True:            # 如果header接收完整            if len(self._buffer) >= 4:                # header部分,按大位元組序轉int,擷取body長度                length, = unpack(">I", self._buffer[0:4])                # 如果body接收完整                if len(self._buffer) >= 4 + length:                    # body部分,protobuf位元組碼                    packet = self._buffer[4:4 + length]                                        # protobuf位元組碼轉成Student對象                    student = StudentMsg_pb2.Student()                    student.ParseFromString(packet)                                        # 調用protobufReceived傳入Student對象                    self.protobufReceived(student)                                        # 去掉_buffer中已經處理的訊息部分                    self._buffer = self._buffer[4 + length:]                else:                    break;            else:                break;    def protobufReceived(self, student):        raise NotImplementedError    def sendProtobuf(self, student):        # Student對象轉為protobuf位元組碼        data = student.SerializeToString()        # 添加Header首碼指定protobuf位元組碼長度        self.transport.write(pack(">I", len(data)) + data)# 邏輯代碼class TcpServerHandle(ProtobufProtocol):    # 實現ProtobufProtocol提供的protobufReceived    def protobufReceived(self, student):        # 將接收到的Student輸出        print 'ID:' + str(student.id)        print 'Name:' + student.name        print 'Email:' + student.email        print 'Friends:'        for friend in student.friends:            print friend        # 建立一個Student並發送給用戶端        student2 = StudentMsg_pb2.Student()        student2.id = 9        student2.name = '伺服器'.decode('UTF-8') # 中文需要轉成UTF-8字串        student2.email = '123@abc.com'        student2.friends.append('X')        student2.friends.append('Y')        self.sendProtobuf(student2)factory = 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;        DataInputStream in = null;                try {            socket = new Socket("localhost", 8080);            out = new DataOutputStream(socket.getOutputStream());            in = new DataInputStream(socket.getInputStream());                        // 建立一個Student傳給伺服器            StudentMsg.Student.Builder builder = StudentMsg.Student.newBuilder();            builder.setId(1);            builder.setName("用戶端");            builder.setEmail("xxg@163.com");            builder.addFriends("A");            builder.addFriends("B");            StudentMsg.Student student = builder.build();            byte[] outputBytes = student.toByteArray(); // Student轉成位元組碼            out.writeInt(outputBytes.length); // write header            out.write(outputBytes); // write body            out.flush();                        // 擷取伺服器傳過來的Student            int bodyLength = in.readInt();  // read header            byte[] bodyBytes = new byte[bodyLength];            in.readFully(bodyBytes);  // read body            StudentMsg.Student student2 = StudentMsg.Student.parseFrom(bodyBytes); // body位元組碼解析成Student            System.out.println("Header:" + bodyLength);            System.out.println("Body:");            System.out.println("ID:" + student2.getId());            System.out.println("Name:" + student2.getName());            System.out.println("Email:" + student2.getEmail());            System.out.println("Friends:");            List<String> friends = student2.getFriendsList();            for(String friend : friends) {            System.out.println(friend);            }        } finally {            // 關閉串連            in.close();            out.close();            socket.close();        }    }}

用用戶端分別測試上面三個TCP伺服器:

伺服器輸出:

ID:1
Name:用戶端
Email:xxg@163.com
Friends:
A
B

用戶端輸出:

Header:32
Body:
ID:9
Name:伺服器
Email:123@abc.com
Friends:
X
Y


作者:叉叉哥   轉載請註明出處:http://blog.csdn.net/xiao__gui/article/details/38864961



誰有spring整合hibernate的項目,不可以用struts架構,如果有與servlet之間通過mina或netty通訊來提供資料

發到你的郵箱了
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.