IOS-----Easy to use Cocoaasyncsocket

Source: Internet
Author: User

Cocoaasyncsocket Useagent's. h file
Gcdasyncsocketdelegate Execute proxy object #import <Foundation/Foundation.h> #import "CocoaAsyncSocket.h" typedef void (^ Didreaddata) (nsdictionary* didreaddata); /** *  Gcdasyncsocketdelegate executing proxy object */@interface nsobjectgcdasyncsocket:nsobject<gcdasyncsocketdelegate>  /** *  received data processing */@property (nonatomic,copy) Didreaddata didreaddata; /** *  data sent  if you add a new key value will need to first open memory */@property (nonatomic,retain) nsmutabledictionary* writedata;  /** *  Send Link Request */-(BOOL) Startconnect; /** *  Single case */+ (nsobjectgcdasyncsocket*) defaultsocket; @end
. m file
nsobjectgcdasyncsocket.m//attendance#import "NSObjectGCDAsyncSocket.h" @implementation Nsobjectgcdasyncsocket {gcdasyncsocket* socket;}/** * Single case * * @return * *+ (Nsobjectgcdasyncsocket *) defaultsocket{//socket is only instantiated onceStatic nsobjectgcdasyncsocket* Socket=nil;//Guaranteed thread safety, defaultsocket only onceStatic dispatch_once_t once;    Dispatch_once (&once, ^ {Socket=[[nsobjectgcdasyncsocket alloc] init];    }); return socket;}/** * Initialize * * * @return Self * *-(instancetype) init{self=[super init]; if (self) {Socket=[[gcdasyncsocket alloc] initwithdelegate:self delega    Tequeue:dispatch_get_global_queue (Dispatch_queue_priority_default, 0)]; } return self;}/** * Send Link request * /-(BOOL) startconnect{//Make sure to disconnect before starting linkif (socket.isconnected) {NSLog (@ "active disconnect");            [Socket disconnect];    } nserror* error;                                     BOOL issuccess= [Socket connecttohost:sockethost Onport:socketport    error:&error];    if (Error) {NSLog (@ "error.localizeddescription:%@", error.localizeddescription);    } return issuccess; } #pragma mark-gcdasyncsocketdelegate/** * Link Successful * * @param sock Sock instance * @param host IP * @param port Port */-(void) Socket: (Gcdasyncsocket *) sock didconnecttohost: (NSString *) host port: (uint16_t) port{//NSLog (@ "%s", _ _FUNCTION__);//NSLog ([email protected] "yes": @ "NO"),//if (sock.isconnected)//{//NSString upload must be added "\ n" delimiter to upload success/ * [sock writedata:[@ "abcabcabcabcabcabc\n" datausingencoding:nsutf8stringencoding] withtimeout:-1 tag:0]; * * / * nsdictionary* [email protected]{@ "Gpsinfo": @ "Gpsinfo", @ "pswd": Self.password, @ "Gpstype": @ (), @ "name":        Self.name,};                                 nsdictionary* [Email protected]{@ "vertion": @ (1), @ "type1": @ (2), @ "type2": @ (0), @ "Type3": @ (0)};*/if ([Nsjsonserialization IsValidJSONObject:self.writeData]) {//NSLog (@ "Isvalidjsonobject");nserror* error;//Turn nsdata and nsstring to ensure the nsdictionary format is unchangedNSData *nsdatauser= [Nsjsonserialization dataWithJSONObject:self.writeData Options:nsjsonwritingprettyprinted Error:            &error]; nsstring* json=[[nsstring Alloc] Initwithdata:nsdatauser encoding:nsutf8st Ringencoding];//NSLog (@ "nsdictionaryuser:%@", JSON);Json=[json stringbyreplacingoccurrencesofstring:@ "\ n" withstring:@ ""]; Json=[json stringbyreplacingoccurrencesofstring:@ "" withstring:@            ""]; Json=[json stringbyappendingstring:@ "\ n"];//NSLog (@ "json:%@", JSON);[Sock Writedata:[json datausingencoding:nsutf8stringencoding] withtimeout:-1 tag:0];//Keep long connections to read[sock readdatawithtimeout:-1 tag:0];                if (Error) {NSLog (@ "localizeddescription:%@", [Error localizeddescription]);            NSLog (@ "localizedfailurereason:%@", [Error Localizedfailurereason]); }                    }//    }}/** * Send data successfully * * @param sock sock instance * @param tag Tag sock */-(void) Socket: (Gcdasyncsocket *) sock Didwritedatawithtag: (long) tag{//NSLog (@ "Didwritedatawithtag");}/** * has obtained data * * @param sock Sock instance * @param data obtained by @param tag tag sock * *-(void) Socket: (Gcdasyncsocket *) sock didreaddata: (NSData *) data withtag: (long) tag{//NSLog (@ "%s", __function__);nserror* Error=nil;                                                       nsdictionary* json= (nsdictionary*) [Nsjsonserialization jsonobjectwithdata:data        Options:nsjsonreadingallowfragments error:&error];    NSLog ([nsjsonserialization isvalidjsonobject:json][email protected] "is Validjsonobject": @ "is ' t validjsonobject");         if (Error) {NSLog (@ "socketerror1:%@", [Error localizeddescription]);    NSLog (@ "socketerror2:%@", [Error Localizedfailurereason]);    } self.didreaddata (JSON);    [Sock disconnect]; }/** * Link Error * * @param sock Sock instance * @param err Error parameter */-(void) Socketdiddisconnect: (Gcdasyncsocket *) sock witherror: (Nserror *) err{//NSLog (@ "%s", __function__);if (err) {NSLog (@ "socketdiddisconnect:%@", [err localizeddescription]);    NSLog (@ "socketdiddisconnect:%@", [err Localizedfailurereason]); }//Self.didreaddata (nil);} @end
Use
Creating Objects    Socket=[Nsobjectgcdasyncsocket defaultsocket];  Fill in the data sent socket.writedata=[nsmutabledictionary dictionarywithdictionary:dictionary];  Process received data        socket.didreaddata=^ (nsdictionary* didreaddata) {...} Start link [Socket startconnect]; Add   cocoaasyncsocket Third library link address: Https://github.com/robbiehanson/CocoaAsyncSocket
Reproduced from the poison of ants

IOS-----Easy to use Cocoaasyncsocket

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.