Giter Site home page Giter Site logo

tcp-split-message-protobuf's Introduction

tcp-split-message-protobuf

111

222

333

b3-1

m4-1

m4-2

tcp split message in receive side; the rpc is protobuf 2; message struct: header+message (header is a int type, indicating the message length)

dependency: protobuf2

reference: http://www.ideawu.net/blog/archives/1027.html

pseudocode:

char tmp[]; Buffer buffer; // 网络循环:必须在一个循环中读取网络,因为网络数据是源源不断的。 while(1){

// 从TCP流中读取不定长度的一段流数据,不能保证读到的数据是你期望的长度

tcp.read(tmp);

// 将这段流数据和之前收到的流数据拼接到一起

buffer.append(tmp);

// 解析循环:必须在一个循环中解析报文,应对所谓的粘包

while(1){

    // 尝试解析报文
    
    msg = parse(buffer);
    
    if(!msg){
    
        // 报文还没有准备好,糟糕,我们遇到拆包了!跳出解析循环,继续读网络。
        
        break;
        
    }
    
    // 将解析过的报文对应的流数据清除
    
    buffer.remove(msg.length);
    
    // 业务处理
    
    process(msg);
    
}

}

step1: proto file to .cc and .h

protoc $PROTO_PATH --cpp_out=. Test.proto

step2: server

g++ serverMultiple.cpp Test.pb.cc -o serverMultiple -lprotobuf -lpthread

step3: client

g++ client.cpp Test.pb.cc -o client -lprotobuf -lpthread

step4:

./serverMultiple

step5:

./client

tcp-split-message-protobuf's People

Contributors

zbcwilliam avatar

Watchers

James Cloos avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.