iOS-----簡易地CocoaAsyncSocket使用,cocoaasyncsocket

來源:互聯網
上載者:User

iOS-----簡易地CocoaAsyncSocket使用,cocoaasyncsocket
CocoaAsyncSocket使用代理的.h檔案

//GCDAsyncSocketDelegate執行代理對象#import <Foundation/Foundation.h>#import "CocoaAsyncSocket.h"typedef void(^DidReadData)(NSDictionary* didReadData);/** *  GCDAsyncSocketDelegate執行代理對象 */@interface NSObjectGCDAsyncSocket : NSObject<GCDAsyncSocketDelegate>/** *  接收到資料的處理 */@property(nonatomic,copy)DidReadData didReadData;/** *  發送的資料  如果添加新索引值則需要先開闢記憶體 */@property(nonatomic,retain)NSMutableDictionary* writeData;/** *  發送連結請求 */-(BOOL)startConnect;/** *  單例 */+(NSObjectGCDAsyncSocket*)defaultSocket;@end
.m檔案
////  NSObjectGCDAsyncSocket.m//  attendance#import "NSObjectGCDAsyncSocket.h"@implementation NSObjectGCDAsyncSocket{    GCDAsyncSocket* socket;}/** *  單例 * *  @return */+(NSObjectGCDAsyncSocket *)defaultSocket{    // socket只會執行個體化一次    static NSObjectGCDAsyncSocket* socket=nil;    // 保證安全執行緒,defaultSocket只執行一次    static dispatch_once_t once;    dispatch_once(&once, ^    {        socket=[[NSObjectGCDAsyncSocket alloc] init];    });    return socket;}/** *  初始化 * * *  @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;}/** *  發送連結請求 */-(BOOL)startConnect{    // 先確定中斷連線再開始連結    if (socket.isConnected)    {        NSLog(@"主動斷開");        [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/** *  連結成功 * *  @param sock sock執行個體 *  @param host IP *  @param port 連接埠 */-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host         port:(uint16_t)port{    //    NSLog(@"%s",__FUNCTION__);//    NSLog(sock.isConnected?@"YES":@"NO");//    if (sock.isConnected)//    { // NSString上傳需要加"\n"分隔字元方可上傳成功/* [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 ([NSJSONSerialization isValidJSONObject:self.writeData])        {//            NSLog(@"isValidJSONObject");            NSError* error;            // 先轉NSData再轉NSString是為了保證NSDictionary格式不變            NSData *nsDataUser= [NSJSONSerialization dataWithJSONObject:self.writeData                                                                options:NSJSONWritingPrettyPrinted                                                                  error:&error];            NSString* json=[[NSString alloc] initWithData:nsDataUser                                                 encoding:NSUTF8StringEncoding];//            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];                        // 保持讀取的長串連            [sock readDataWithTimeout:-1                                  tag:0];                        if (error)            {                NSLog(@"localizedDescription:%@",[error localizedDescription]);                NSLog(@"localizedFailureReason:%@",[error localizedFailureReason]);            }                    }//    } }/** *  發送資料成功 * *  @param sock  sock執行個體 *  @param tag  標記sock */-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{//    NSLog(@"didWriteDataWithTag");}/** *  已經擷取到資料 * *  @param sock sock執行個體 *  @param data 擷取到的資料 *  @param 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]?@"is ValidJSONObject":@"is't ValidJSONObject");    if (error)    {        NSLog(@"socketError1:%@",[error localizedDescription]);         NSLog(@"socketError2:%@",[error localizedFailureReason]);    }    self.didReadData(json);    [sock disconnect];    }/** *  連結出錯 * *  @param sock sock執行個體 *  @param err  錯誤參數 */-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{//    NSLog(@"%s",__FUNCTION__);        if (err)    {        NSLog(@"socketDidDisconnect:%@",[err localizedDescription]);        NSLog(@"socketDidDisconnect:%@",[err localizedFailureReason]);    }//    self.didReadData(nil);}@end
使用
建立對象    socket=[NSObjectGCDAsyncSocket defaultSocket];填寫發送的資料socket.writeData=[NSMutableDictionary dictionaryWithDictionary:dictionary];處理收到的資料        socket.didReadData=^(NSDictionary* didReadData){.......}開始連結[socket startConnect];添加CocoaAsyncSocket 第三庫 連結地址:https://github.com/robbiehanson/CocoaAsyncSocket
轉載自螻蟻之毒

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.