In C ++, messages are automatically distributed to the third about JSON encode.

Source: Internet
Author: User
ArticleDirectory
    • 1. Use Cases
    • 2. Use IDL to generate C ++ code:
    • 3. How to Implement encode and decode
    • 4. Todo

The first part of the "C ++ automatic message dispatching" series introduces the IDL parser, the generated C ++CodeOnly JSON to C ++ struct is supported. After new refactoring, the support for converting C ++ struct to JSON is added this time. The IDL parser automatically generates two methods for C ++ struct.

Decode: Convert JSON to C ++ struct.

Encode: converts C ++ struct to a JSON string.

In practical applications, network serversProgramThe process is as follows:

1> receiving client messages asynchronously at the network layer (all applications discussed in this article are based on the JSON Protocol)

2> parse the message, such as determining the message type, checking the message body field, parsing, and assigning values. Encapsulate parsed results into a specific struct (each Message Type defines a separate struct ). Note: JSON parsing, checking, and values are all completed by network threads (multithreading). Generally, the core logic of the server program is completed in a single thread, so the logic thread should focus on "protection. After the message is converted to struct, the logic thread operates the binary directly to maximize the real-time and throughput of the logic thread.

3> after the logic thread finishes processing the request, it usually produces a specific response result (sometimes one, such as RPC request, and sometimes multiple, such as broadcast messages ). The response results must still be sent to the client over the JSON protocol.

4> logically generate the response result as a binary struct, which needs to be converted to a JSON string. Similarly, these time-consuming and logically independent operations should be placed in the network thread. The principle is the same, to the greatest extent possible

The efficiency of the logic layer.

Complete sample code SVN Co http://ffown.googlecode.com/svn/trunk/fflib/lib/generator/

1. Use Cases

Assume that a player can query friend information. The client sends a get_friends_req request with the UID parameter. The server queries the friends of the user and generates a list of friends to return the message result.

First, define the IDL file, which has two message bodies:

 
//! Define the Request Message Type:
StructGet_friends_req_t
{
Uint32 uid;
};

//! Defines the type of the Server Response Message Body, ending with ret_t, which indicates that the message is a response message and the server does not need to process the request for this message.
 
StructAll_friends_ret_t
{
Array <uint32> friends;
};

The corresponding server implementation code is as follows:

1> socket_t encapsulates the Linux socket file descriptor operation. Here is just an example. It provides the async_write interface to send data in preactor mode. It accepts the base class pointer of all messages, and the pointer is a smart pointer without manual analysis. The message body base class supports the encode interface. The binary struct is converted into a JSON string, and the socket sends the JSON string to the client through the Write System Call.

2> logic_service_t logic layer to process all message requests. Reload a handle function for each message definition. In order to avoid uploading messages to the logical layer for memory copying at the network layer, smart pointers are used and manual management is avoided.

3> msg_dispather_t. This class is automatically generated by the IDL parser. in the production environment, a network layer should call this object. Because this article is only an example, the network layer is ignored and called by the main simulated network layer.

 Class Socket_t
{
Public :
Void Async_write (msg_ptr_t MSG _)
{
// ! Todo do Io write
Cout < " Wile send: " <MSG _-> encode_json () < " \ N " ;
}
};

Typedef socket_t * socket_ptr_t;

Class Logic_service_t
{
Public :
Void Handle (shared_ptr_t <get_friends_req_t> req _, socket_ptr_t SOCK _)
{
Cout < " REQ uid: " <Req _-> uid < " \ N " ;
// ! Do some logic code
Shared_ptr_t <all_friends_ret_t> MSG ( New All_friends_ret_t ());

For ( Int I = 0 ; I < 10 ; ++ I)
MSG-> friends. push_back (I );

SOCK _-> async_write (MSG );
}
};


Int Main ( Int Argc, Char * Argv [])
{
Try
{
String TMP = " {\ "Get_friends_req_t \": {\ "uid \": 12345 }} " ;
Logic_service_t logic_service;
Msg_dispather_t <logic_service_t, socket_ptr_t> msg_dispather (logic_service );
// ! This should be called by the network layer.
Socket_ptr_t sock = New Socket_t ();
Msg_dispather.dispath (TMP, sock );
}
Catch (Exception & E)
{
Cout < " E: " <E. What () < " \ N " ;
}
Cout < " Main end OK \ n " ;
}
2. Use IDL to generate C ++ code:

Idl_generator.py example. IDL msg_def.h

The example. IDL previously defined generates the header file msg_def.h after idl_generator.py analysis, including the implementation of msg_dispather_t. The main code is:

 Struct All_friends_ret_t: Public Msg_t {
Vector <uint32> friends;
Int Parse ( Const Json_value_t & jval _){

Json_instream_t In ( " All_friends_ret_t " );
In . Decode (" Friends " , Jval _[ " Friends " ], Friends );
Return 0 ;
}

String Encode_json () Const
{
Rapidjson: Document: allocatortype Allocator;
Rapidjson: stringbuffer str_buff;
Json_value_t ibj_json (rapidjson: kobjecttype );
Json_value_t ret_json (rapidjson: kobjecttype );

This -> Encode_json_val (ibj_json, Allocator );
Ret_json.addmember ( " All_friends_ret_t " , Ibj_json, Allocator );

Rapidjson: writer <rapidjson: stringbuffer> writer (str_buff, & Allocator );
Ret_json.accept (writer );
String Output (str_buff.getstring (), str_buff.size ());
Return Output;
}

Int Encode_json_val (json_value_t & DEST, rapidjson: Document: allocatortype & Allocator) Const {

Json_outstream_t Out (Allocator );
Out . Encode ( " Friends " , DEST, Friends );
Return 0 ;
}

};
3. How to Implement encode and decode

By continuously developing the IDL parser, The JSON parsing and encoding are further optimized. Where:

1> json_instream.h completes JSON decode, traverses fields in struct in sequence, and assigns values to fields. In json_instream_t, the decode parameter that supports all types of parameters is reloaded.

2> json_outstream.h converts struct to JSON, traverses fields in struct in sequence, converts them to JSON value, and reloads the encode parameter that supports all basic types.

Sample Code:

Json_outstream_t & encode ( Const   Char * Filed_name _, json_value_t & jval _, int8_t DEST _);
Json_outstream_t & encode ( Const Char * Filed_name _, json_value_t & jval _, uint8_t DEST _);
Json_outstream_t & encode (Const Char * Filed_name _, json_value_t & jval _, int16_t DEST _);
Json_outstream_t & encode ( Const Char * Filed_name _, json_value_t & jval _, uint16_t DEST _);
Json_outstream_t & encode ( Const Char * Filed_name _, json_value_t & jval _, int32_t DEST _);
Json_outstream_t & encode ( Const Char * Filed_name _, json_value_t & jval _, uint32_t DEST _);
Json_outstream_t & encode (Const Char * Filed_name _, json_value_t & jval _, int64_t DEST _);
Json_outstream_t & encode ( Const Char * Filed_name _, json_value_t & jval _, uint64_t DEST _);
Json_outstream_t & encode ( Const Char * Filed_name _, json_value_t & jval _, Bool DeST _);
Json_outstream_t & encode ( Const Char * Filed_name _, json_value_t & jval _,Float DeST _);
Json_outstream_t & encode ( Const Char * Filed_name _, json_value_t & jval _, Const String & DEST _);
4. Todo

1. The IDL parser has implemented basic functions. The next time you plan to use this IDL parser to implement a chat server.

2. Added support for Binary encode/decode in The IDL parser.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.