iOS即时通讯

项目中需要写一个小型的群组聊天,用了github上搜到的一个第三方库GCDAsyncsocket,现在整理一下使用过程。

配置大概就是以下,好像没有漏掉什么

1,下载GCDAsyncsocket库;

2.将GCDAsyncSocket.h、GCDAsyncSocket.m、GCDAsyncUdpSocket.h和GCDAsyncUdpSocket.m四个文件拉进你的项目中;

3.添加CFNetwork.framework库;

使用的时候最好创建一个单例类,这样开启和关闭socket都比较方便。
Singleton.h

#import 
#import "GCDAsyncSocket.h"
#import "GroupChatModel.h"
#define DEFINE_SHARED_INSTANCE_USING_BLOCK(block) \
static dispatch_once_t onceToken = 0; \
__strong static id sharedInstance = nil; \
dispatch_once(&onceToken, ^{ \
sharedInstance = block(); \
}); \
return sharedInstance; \

#define HOST_IP @"192.168.0.30"
#define HOST_PORT 9988
@protocol SingletonDelegate 

- (void)socketDidReadData:(GroupChatModel *)model;//接受消息
- (void)sockContectSuccess;

@end

@interface Singleton : NSObject

@property (nonatomic, strong) GCDAsyncSocket    *socket;       // socket
@property (nonatomic, copy  ) NSString       *socketHost;   // socket的Host
@property (nonatomic, assign) UInt16         socketPort;    // socket的prot
@property (nonatomic, retain) NSTimer        *connectTimer; // 计时器
@property (nonatomic, assign)BOOL isContectSuccess;
@property (nonatomic, retain) NSMutableArray *delegates;
//@property (nonatomic, assign) iddelegate;
+ (Singleton *)sharedInstance;
-(void)socketConnectServer;//socket连接
-(void)cutOffSocket; // 断开socket连接

- (void)socketWriteData:(NSData *)data;//发送
-(void)addDelegates:(id)delegate;
-(void)removeDelegates:(id)delegate;
@end

Singleton.m中,创建对象

+(Singleton *) sharedInstance
{
    static Singleton *sharedInstace = nil;
    static dispatch_once_t onceToken;
    dispatch_queue_t aQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_once(&onceToken, ^{
        
        sharedInstace = [[self alloc] init];
        sharedInstace.delegates = [NSMutableArray arrayWithCapacity:1];
        sharedInstace.socket    = [[GCDAsyncSocket alloc] initWithDelegate:sharedInstace delegateQueue:aQueue];
    });
    
    return sharedInstace;
}

socket连接

-(void)socketConnectServer{
    // 在连接前先进行手动断开
    [[Singleton sharedInstance] cutOffSocket];
    // 确保断开后再连,如果对一个正处于连接状态的socket进行连接,会出现崩溃
    [Singleton sharedInstance].socket.userData = SOCKETOFFLINEBYSERVER;
    [[Singleton sharedInstance] socketConnectHost];
}

-(void)socketConnectHost{
    if (!self.socket) {
    }
    NSError *error = nil;
    [self.socket connectToHost:HOST_IP onPort:HOST_PORT withTimeout:3 error:&error];
}

切断socket

-(void)cutOffSocket{
    _isContectSuccess = NO;
    self.socket.userData = SOCKETOFFLINEBYUSER;// 声明是由用户主动切断
    
    [self.connectTimer invalidate];
    
    [self.socket disconnect];
}

连接错误时会掉这个方法,在这里协议进行重连

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(nullable NSError *)err
{
    _isContectSuccess = NO;
    NSLog(@"sorry the connect is failure %@",sock.userData);
    if (![sock.userData isEqualToString:SOCKETOFFLINEBYUSER]) {
        // 服务器掉线,重连
//        [self socketConnectHost];
    }
    else {
        // 如果由用户断开,不进行重连
        return;
    }
}

连接之后开始调用这个协议方法读数据

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSLog(@"didReadData read data");
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    GroupChatModel *model = [GroupChatModel initializeDictoinary:jsonDict];
    [sock readDataWithTimeout:-1 tag:200];
    // 对得到的data值进行解析与转换即可
    dispatch_async(dispatch_get_main_queue(), ^{
        for (id delegate in  self.delegates) {
            if (delegate && [delegate respondsToSelector:@selector(socketDidReadData:)]) {
                [delegate socketDidReadData:model];
            }
        }

    });
}

调用此方法写数据

- (void)socketWriteData:(NSData *)data{
    [self.socket writeData:data withTimeout:1 tag:0];
}

注意:单例类的协议方法中调用GCDAsyncsocket的协议方法,是为了简化使用,也可以直接使用GCDAsyncsocket的协议方法,这些都是我搜到的一些帖子中别人介绍的,好东西分享一下,原来的文章找不到是哪一篇了,对原作者表示歉意。
在用的过程中也遇到了好几个坑,但是现在感觉忘记了,如果使用过程中遇到问题的,可以联系我,我可能也不能帮你解决,刚写这个,思路不太清晰。

你可能感兴趣的:(iOS即时通讯)