Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Application scenario: The APP side integrates CocoaAsyncSocket to communicate with the server side to realize robot functions.

I. Knowledge reserve

1.1 Tweak What is tweak?

Tweak is essentially a dynamic library for ios. There are two types of dynamic libraries on the IOS platform, dylib and Framework. Libsqlite.dylib libz.dylib libsqlite.dylib libz.dylib libsqlite.dylib Tweak uses a dynamic library like Dylib.

In jailbreak development, the various cracking patches are collectively referred to as tweaks. IOS Tweak basically relies on a dynamic library of Cydia Substrate, the work of Cydia author Jay Freeman. Its main function is to hook an App to modify code, such as replacing the implementation of its methods. Tweak on Cydia is implemented based on Mobile Substrate.

iPhone:~ root# cd /Library/MobileSubstrate/DynamicLibraries

Copy the code

We can in the device’s/Library/MobileSubstrate/DynamicLibraries directory to see all the tweak there on his mobile phone. In addition to dylib, there are files in the plist format, which identifies the scope of tweak, and bundles, which are the resource files used by tweak.

The installation of those

Blog.csdn.net/z929118967/…

1.2 long connection

  • The HTTP request:

Each time the data is updated, a request is sent to the corresponding port, and the connection is closed after the data is returned

  • A long connection

The client and server are connected all the time. When data is updated, the server directly sends it to the client without the client actively requesting it. (The client needs to listen for input to the stream)

Ps: in the process, to ensure that the server and the client has been the connection state, the client will be uninterrupted send a heartbeat data to the server regularly, that is connected to, or long time no data update, will be disconnected, this has always been the heart data, will ensure the connection without interruption, as to the content of the heart rate data, That is, the front end and the back end negotiate together, and the requested data is separate. (Nstimer is usually used)

  • Short connection, parallel connection, persistent connection and long connection

Blog.csdn.net/z929118967/…

II. Integrate CocoaAsyncSocket with Logos Tweak template from MonkeyDev

Because it supports CocoaPods, you can use Node.js to build the corresponding server.

2.1 Settings for Reading Messages

  • The default message read timeout can be set to 10
- (void)socketWriteData:(NSString *)data {
    // Start writing data
    NSLog(@ "socketWriteData: % @",data);
    
    NSData *requestData = [data dataUsingEncoding:NSUTF8StringEncoding];
    [self.socket writeData:requestData withTimeout:- 1 tag:0];
// [self socketBeginReadData]; // Change to listen immediately after the connection is established
}
Copy the code

If you want to listen to the server’s message push in real time, you can change it to read as soon as the connection is established

- (void)socket:(GCDAsyncSocket *)socket didConnectToHost:(NSString *)host port:(UInt16)port {

        [self.socketManager socketBeginReadData];// Change to listen immediately after the connection is established

}
Copy the code
  • Start reading data
/** Start reading data */
#pragmaMark-******** sets a timeout for reading data and starts listening for reading data after the connection is established

- (void)socketBeginReadData {
    NSLog(@"socketBeginReadData");
    [self.socket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:- 1 maxLength:0 tag:0];// Consider using -1
}
Copy the code

2.2 Processing of service logic

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {

// According to the type of message returned by the server, the parameters are parsed and the task is processed
}
Copy the code

2.3 Methods to realize real-time monitoring of the flow on the server

Start the next listening input stream as soon as data is received: Receive Data – socketBeginReadData

2.4 Distinguish the modes of active push and response on the server

The two are distinguished as follows:

  • You can have the server add response types to differentiate
  • The APP end determines whether the response data contains the reqId, which exists only when the app actively initiates the request response

Handles server side message push


    GACRESPONSE_TYPE respType = [json[@"respType"] integerValue];
    
    if(respType == RESPONSE_TYPE_NOTIFY){// Message notification Active notification of the server
        
        // Send notifications directly
        // select * from RESPONSE_TYPE_NOTIFY ()
        
        NSMutableDictionary * userInfo = [NSMutableDictionary dictionaryWithObject:json forKey:kRESPONSE_TYPENotificationjsonKey];//respType 传送json
        [[NSNotificationCenter defaultCenter] postNotificationName:kRESPONSE_TYPERESPONSE_TYPE_NOTIFYNotification object:self userInfo:userInfo];
        
        
    }else{
        //2. Execute the corresponding block
        
        
        
        SocketDidReadBlock didReadBlock = self.requestsMap[requestID];
        
        // if (errorCode ! = 0) {
        //
        // jsonError = [[NSError alloc]initWithDomain:NSURLErrorDomain code:errorCode userInfo:nil];
        / /}
        
        if(didReadBlock) { didReadBlock(jsonError, json); }} [self.socketManager socketBeginReadData];// Change to listen immediately after the connection is established
Copy the code

2.5 Handling abnormal Disconnection

  • Failed to reconnect

#pragmaMark-******** Failed to reconnect
- (void)socketDidDisconnect:(GCDAsyncSocket *)socket withError:(NSError *)err {
Copy the code
  • Determination of connection failure
- (void)socketWriteDataWithRequestType:(GACRequestType)type
                           requestBody:(nonnull NSDictionary *)body
                            completion:(nullable SocketDidReadBlock)callback {
    NSLog(@ "socketWriteData: % @",body);
    if (self.socketManager.connectStatus == - 1) {
        NSLog(@" Socket disconnected");

Copy the code
  • The connection is successful
- (void)socket:(GCDAsyncSocket *)socket didConnectToHost:(NSString *)host port:(UInt16)port {
    
    self.socketManager.connectStatus = 1;// The state is set in advance to where the connection is established
   // Delete the reconnected clock
    [self.socketManager invalidatereconnectTimer];
Copy the code

2.6 Common Problems

Question:

GCDAsyncSocketCommunicationManager.m:41:1: Cannot synthesize weak property in file using manual reference counting

Copy the code

Solution: Modify the project configuration to the ARC compilation environment

Modify app llVMXX-language-object-c to support ARC

The sequence is y-Y-Y-no

2.7 download the demo

CSDN resource download demo source code from https://download.csdn.net/download/u011018979/15136868

  • Establish a connection
#pragma mark - ******** CMessageMgr init

- (CMessageMgr *)init

{
    %log(a); CMessageMgr *ret = %orig; globalMessageMgr =ret; id fromUser = [%c(SettingUtil) getLocalUsrName:0]; // If you haven't logged in to wechat, you can't get itif ( fromUser == nil/* condition */)
    {
        return ret ;
        /* code */
    }
    
    CContactMgr *contactMgr = [[objc_getClass("MMServiceCenter") defaultCenter] getService:objc_getClass("CContactMgr")];
    CContact *selfContact = [contactMgr getSelfContact];
    
    //NSLog(@" selfContact :%@", selfContact); //MMSessionInfo /** ConnectConfig = [[GACConnectConfig alloc] init]; //MMSessionInfo /** ConnectConfig = [GACConnectConfig alloc] init]; _connectConfig.channels = @"dkf";
    _connectConfig.currentChannel = @"dkf"; _connectConfig.host = KconnectConfighost; _connectConfig.port = [KconnectConfigport intValue]; _connectConfig.socketVersion = 5; _connectConfig.WeChatNum = fromUser; _connectConfig.token = @"f14c431d1a6efa9"; _connectConfig.selfContact =selfContact; / / 1. Custom configuration environment [[GCDAsyncSocketCommunicationManager sharedInstance] createSocketWithConfig: _connectConfig]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupRESPONSE_TYPE: name:kRESPONSE_TYPENotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupRESPONSE_TYPENOTIFY:) name:kRESPONSE_TYPERESPONSE_TYPE_NOTIFYNotification object:nil]; //return ret;
    
}


Copy the code
  • Handles message delivery tasks

Dependent third party library :CocoaAsyncSocket

platform :ios, '8.0'
inhibit_all_warnings!

#use_frameworks!
target 'wlentrust' do
   pod 'CocoaAsyncSocket'
   pod 'JSONModel'.'1.1.0'
   pod 'AFNetworking'.'3.0.4'
   pod 'XMLDictionary'
end
Copy the code

see also

For more, check out # Applets: iOS Reverse, which presents valuable information only for you, focusing on the mobile technology research field.