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

來源:互聯網
上載者:User

標籤:dha   UI   cli   net   bsp   netty   建立   dsl   編碼   

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) {            // 讀取client傳過來的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對象傳到client        StudentMsg.Student.Builder builder = StudentMsg.Student.newBuilder();        builder.setId(9);        builder.setName("server");        builder.setEmail("[email protected]");        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;}}}}

MINAserver加入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 {    // 讀取client傳過來的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對象傳到client        StudentMsg.Student.Builder builder = StudentMsg.Student.newBuilder();        builder.setId(9);        builder.setName("server");        builder.setEmail("[email protected]");        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並發送給client        student2 = StudentMsg_pb2.Student()        student2.id = 9        student2.name = ‘server‘.decode(‘UTF-8‘) # 中文須要轉成UTF-8字串        student2.email = ‘[email protected]‘        student2.friends.append(‘X‘)        student2.friends.append(‘Y‘)        self.sendProtobuf(student2)factory = Factory()factory.protocol = TcpServerHandlereactor.listenTCP(8080, factory)reactor.run()


以下是Java編寫的一個client測試程式:

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傳給server            StudentMsg.Student.Builder builder = StudentMsg.Student.newBuilder();            builder.setId(1);            builder.setName("client");            builder.setEmail("[email protected]");            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();                        // 擷取server傳過來的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();        }    }}

用client分別測試上面三個TCPserver:

server輸出:

ID:1
Name:client
Email:[email protected]
Friends:
A
B

client輸出:

Header:32
Body:
ID:9
Name:server
Email:[email protected]
Friends:
X
Y


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

MINA、Netty、Twisted一起學系列

MINA、Netty、Twisted一起學(一):實現簡單的TCPserver

MINA、Netty、Twisted一起學(二):TCP訊息邊界問題及按行切割訊息

MINA、Netty、Twisted一起學(三):TCP訊息固定大小的首碼(Header)

MINA、Netty、Twisted一起學(四):定製自己的協議

MINA、Netty、Twisted一起學(五):整合protobuf

MINA、Netty、Twisted一起學(六):session

MINA、Netty、Twisted一起學(七):公布/訂閱(Publish/Subscribe)

MINA、Netty、Twisted一起學(八):HTTPserver

MINA、Netty、Twisted一起學(九):非同步IO和回呼函數

MINA、Netty、Twisted一起學(十):執行緒模式

MINA、Netty、Twisted一起學(十一):SSL/TLS

MINA、Netty、Twisted一起學(十二):HTTPS

原始碼

https://github.com/wucao/mina-netty-twisted


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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.