LLSocketManager
安装
LLSocketManager 通过 CocoaPods 提供。要安装它,只需在你的 Podfile 中添加以下行:
pod 'LLSocketManager'
使用
#import <LLSocketManager/LLSocketManager.h>
// 配置 host、port 以及代理对象
[LLSocketManager.share setupHost:@"xxxx.xxxx.xxxx.xxxx" port:8001 delegate:AObject];
// 链接 socket
[LLSocketManager.share connectHost];
LLSocketManager
会自动帮你重连,发送心跳包以保持长连接。你所需做的就是设置一个遵循 LLSocketProtocol
协议的代理对象,该协议允许你完成一些功能设置,其中必须实现的是从服务端 socket
收到消息的转发功能。
例如新建一个 LLSocketHandler
实例
#import <LLSocketManager/LLSocketManager.h>
@interface LLSocketHandler : NSObject <LLSocketProtocol>
@end
@implementation LLSocketHandler
/// socket 连接成功
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
// 发送一些额外的信息,例如客户端信息
}
/// 发送心跳包数据
-(void)sendKeepAliveData:(GCDAsyncSocket *)sock{
// 在这里发送心跳包数据
// 例如:[LLSocketManager.share sendMessage:[LLSocketMessage message:@"KEEPALIVE<EOF>"]];
}
/// socket 收到了数据
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
NSString* dataContent = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
LLLog(@"收到 socket 消息:%@",dataContent);
// 在这里进行 socket 的处理和转发
}
@end
许可协议
LLSocketManager 遵循 MIT 许可协议。更多信息请查阅 LICENSE 文件。