Socket Communication Practice in iOS development-Request packet encoding module, ios-request

Source: Internet
Author: User
Tags constant definition

Socket Communication Practice in iOS development-Request packet encoding module, ios-request


In fact, most of the network communication used in iOS application development is http/https. Unless there are special requirements, the Socket network protocol is used for network data transmission, at this time, the iOS client requires a good third-party CocoaAsyncSocket to connect to and transmit data, the third-party address: bytes.

In some applications that require less Socket communication, such as instant messaging between multiple iOS devices, CocoaAsyncSocket can basically meet this requirement, however, in my own live broadcast project, the requirements for Socket communication protocols are relatively high. This requirement mode is similar to the game development mode, because a lot of data changes in game applications require real-time data updates, such as the player's life value, your device needs to update the lifecycle data of other players in real time, while other player devices also need to update your lifecycle data in real time. This requirement cannot be met through http active requests, therefore, game development usually involves Socket communication. The background language used in my live broadcast project is erlang. The background has a custom protocol rule for the data transmitted through this Socket protocol. For example:

Figure 1

This protocol is a binary stream that can be transmitted in the Socket. The third part of the protocol data stream is the specific data field to be transmitted,

The content of this protocol data stream is an example of a protocol document via erlang:

// ============ Switch to a new scenario ==============
Message Cs_20001 {
Uint8 SceneId = 1; // enter the scenario ID
Uint32 Line = 2; // split the Line. If the common scenario is 0, the backend of the multi-user copy will specify

String message = 3; // message
}
Message SC _20001 {
Uint8 Res = 1; // 1 success 0 exception 2 cannot enter this level 3 is already in the level when it is 4 No this map or Level 5 today into the BOSS off or general off the number of times limit 6 physical strength less 7 enter conditions less than 8 the map type does not exist. 10 is not involved in the BOSS activity, unable to enter the 11 BOSS Battle Room status has ended 12 times less than 13 cooling time less than 14 no permission to enter this BOSS room 15 into the BOSS room insufficient conditions
Uint32 SceneId = 2; // The current scenario
Uint8 Pos = 3; // coordinate point
Uint8 Status = 4; // character Status 0 normal 10 captain Status
Uint8 Type = 5; // front-end ID
Uint32 DefaultCombat = 6; // recommendation capability

String message = 7; // message
}
First, let's explain some definitions of this Protocol:
Cs is the Client --> Server (the Data Protocol sent by the Client to the Server), and SC is the Server --> Client (the data protocol returned by the Server to the Client)

This article mainly describes the request module, so we will talk about the Cs_20001 Request Protocol packet encapsulation. This 20001 is the Protocol Number, also known as the protocol ID (which will be used later in the Code ).

In Cs_20001, there are two fields that need to be sent by Socket to the server, both in uint32 format and basic data type of C language. However, binary streams are transmitted in Socket transmission, that is, we need to convert the two uint32 data fields into binary data, splice them into a data stream, and then let the data stream pass through the Socket to the server, speaking of streaming, it is easier to understand the concept of streaming if you have learned Java, and it doesn't matter if you don't have access to streaming. It is like a piece of water flow flowing from the client to the server. In fact, this data stream is transmitted from the client to the server. This process is not as simple as imagined. It involves many underlying Socket transmission logic, but CocoaAsyncSocket has completed this encapsulation, in addition, it is an OC object-oriented encapsulation. We only need to convert the data to NSData and pass it through the CocoaAsyncSocket proxy method.

For simple requirements, for example, I only need two iPhone devices to transmit the NSString, as long as the NSString is converted to NSData for transmission, but for the erlang server I mentioned above, we need to customize the protocol, the client needs more packaging logic to unpackage. For example, taking the preceding field protocol as an example, the Cs_20001 data packet is spliced according to the custom format in Figure 1, in this case, the Protocol Number of two bytes in Figure 1 is 20001, that is, 20001 needs to be stored in two bytes of storage space. Then, in Figure 1, the content of the protocol data stream is the data merged by the uint32 SceneId and uint32 Line fields, and the Protocol specifies the order in which the ordered data is spliced, here, the uint32 SceneId is first while the uint32 Line is later. After splicing, we can calculate the number of bytes of the protocol data stream? Bytes, then + 2 (the byte length of the Protocol Number), and + 4 (the four bytes required for the total message length) to get the length of the entire Protocol stream, then, the total length is stored in the total length of four bytes of messages. Of course, the splicing order of the entire Protocol stream from left to right is shown in 1, and then passed to the server through CocoaAsyncSocket.

The following code explains the business logic:

I. First, Model the backend protocol. Whenever there is an MVC foundation, you should understand it in seconds. It is actually the Model in MVC.

Figure 2

Ii. Use this model

Figure 3

3. Because binary bytecode is transmitted in the Socket communication protocol, attributes in the model, such as sceneId, line, and message, must be converted to the byte type respectively, then it is converted to NSData (the OC end requires NSData) and then transmitted through Socket. This process is called "encoding". The encoding must be spliced in order.

Figure 4

Retrieve the type and value one by one based on the model object attributes during runtime and convert the value to byte bytecode Based on the type, then convert to the binary object type of the OC of NSData.

The type of the attribute here is actually specified by OC. If you do not know it, you can print all the types of results during the above running.

The above Cs_20001 data packet model object is encoded and NSLog is printed to check the value and type:

Figure 5

Looking at this result, we can see that the uint8_t type is TC, the uint32_t type is TI, and the NSString type is T @ "NSString". Of course there are many other types that can be printed and viewed by yourself, or Google search.

Then we will explain the TYPE _... Of the rows 70, 73, 76, 79, and 82 in figure 4, which is actually a constant definition:

Figure 6

The tool class interface used for encoding:

Figure 7

Implementation of specific encoding and decoding:

1 # import "YMSocketUtils. h "2 3 @ implementation YMSocketUtils 4 5/** 6 * reverse byte sequence 7*8 * @ param srcData original byte NSData 9*10 * @ return Reverse Sequence back byte NSData 11*/12 + (NSData *) dataWithReverse :( NSData *) srcData 13 {14 // NSMutableData * dstData = [[NSMutableData alloc] init]; 15 // for (NSUInteger I = 0; I <srcData. length; I ++) {16 // [dstData appendData: [srcData subdataWithRange: NSMakeRange (srcData. length-1-i, 1)]; 17 //} // for 18 19 NSUInteger byteCount = srcData. length; 20 NSMutableData * dstData = [[NSMutableData alloc] initWithData: srcData]; 21 NSUInteger halfLength = byteCount/2; 22 for (NSUInteger I = 0; I 

The rest left for the reader to download this Demo to see the code, link: http://pan.baidu.com/s/1hsi7tNQ password: byiy

 

Respect the labor results, repost the source, and indicate the source; Socket communication practice developed by iOS -- Request data packet encoding Module

 

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.