CocoaAsyncSocket, cocoaasyncsocket

Source: Internet
Author: User

CocoaAsyncSocket, cocoaasyncsocket

Proxy. h file

// GCDAsyncSocketDelegate executes the proxy object # import <Foundation/Foundation. h> # import "CocoaAsyncSocket. h "# import" Public. h "typedef void (^ DidReadData) (NSDictionary * didReadData);/*** GCDAsyncSocketDelegate executes the proxy object */@ interface NSObjectGCDAsyncSocket: NSObject <GCDAsyncSocketDelegate>/*** process received data */@ property (nonatomic, copy) DidReadData didReadData; /*** if a new key value is added to the sent data, you need to first open up the memory */@ property (nonatomic, retain) NSMutableDictionary * writeData; /*** send link Request */-(BOOL) startConnect;/*** Singleton */+ (NSObjectGCDAsyncSocket *) defaultSocket; @ end

. M file

/// NSObjectGCDAsyncSocket. m // attendance /// Created by dgc on 15/7/7. // Copyright (c) 2015 dgc. all rights reserved. // # import "NSObjectGCDAsyncSocket. h "@ implementation NSObjectGCDAsyncSocket {GCDAsyncSocket * socket;}/*** Singleton ** @ return */+ (NSObjectGCDAsyncSocket *) defaultSocket {// socket will only instantiate static NSObjectGCDAsyncSocket * socket = nil; // ensure thread security. defaultSocket only executes static 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 delegateQueue: dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];} return self;}/*** send link Request */-(BOOL) startConnect {// first confirm to disconnect and then start to link if (socket. isConnected) {NSLo G (@ "active disconnection"); [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 instance * @ param host IP * @ param port */-(void) socket :( GCDAsyncSocket *) sockdidConnectToHost :( NSSt Ring *) host port :( uint16_t) port {// NSLog (@ "% s" ,__ FUNCTION _); // NSLog (sock. isConnected? @ "YES": @ "NO"); // if (sock. isConnected) // {// nsstring upload must be completed with the "\ n" separator./* [sock writeData: [@ "ABCABCABCABCABCABC \ n" dataUsingEncoding: NSUTF8StringEncoding] withTimeout: -1 tag: 0]; * // * NSDictionary * nsDictionaryUser ={ @ "gpsinfo": @ "Gpsinfo", @ "pswd": self. passWord, @ "gpstype": @ (2015), @ "name": self. name,}; NSDictionary * agrement = @ {@ "vertion": @ (1), @ "type1": @ (2), @ "type2": @ (0 ), @ "type3": @ (0)}; */if ([NS JSONSerialization isValidJSONObject: self. writeData]) {// NSLog (@ "isValidJSONObject"); NSError * error; // first convert nsdata to nsstring to ensure the nsdictionary format remains unchanged NSData * nsDataUser = [NSJSONSerialization dataWithJSONObject: self. writeData options: Unknown error: & error]; NSString * json = [[NSString alloc] initWithData: nsDataUser encoding: NSUTF8StringEncoding]; // NSLog (@ "nsDictionaryUser: % @", json); json = [Json stringByReplacingOccurrencesOfString: @ "\ n" withString: @ ""]; json = [json Syntax: @ "" withString: @ ""]; json = [json stringByAppendingString: @ "\ n"]; // NSLog (@ "json: % @", json); [sock writeData: [json dataUsingEncoding: NSUTF8StringEncoding] withTimeout:-1 tag: 0]; // keep the read persistent connection [sock readDataWithTimeout:-1 tag: 0]; if (error) {NSLog (@ "localizedDescription: % @", [error localize DDescription]); NSLog (@ "localizedFailureReason: % @", [error localizedFailureReason]);} //}/*** data transmission succeeded ** @ param sock instance * @ param tag mark sock */-(void) socket :( GCDAsyncSocket *) sockdidWriteDataWithTag :( long) tag {// NSLog (@ "didWriteDataWithTag ");} /*** data obtained ** @ param sock instance * @ param data the data obtained * @ param tag mark sock */-(void) socket :( GCDAsyncSocket *) sock didReadData :( NSData *) data withT Ag :( long) tag {// NSLog (@ "% s" ,__ FUNCTION _); NSError * error = nil; NSDictionary * json = (NSDictionary *) [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingAllowFragments error: & error]; NSLog ([NSJSONSerialization isValidJSONObject: json]? @ "Is ValidJSONObject": @ "is't ValidJSONObject"); if (error) {NSLog (@ "socketError1: % @", [error localizedDescription]); NSLog (@ "socketError2: % @", [error localizedFailureReason]);} self. didReadData (json); [sock disconnect];}/*** Link error ** @ param 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

Create object socket = [NSObjectGCDAsyncSocket defaultSocket]; fill in the Data socket sent. writeData = [NSMutableDictionary dictionaryWithDictionary: dictionary]; process received data socket. didReadData = ^ (NSDictionary * didReadData ){.......} start [socket startConnect];

 

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.