备注:项目中需要放弃掉XMPP框架,自定义Socket长链接去进行通信的实现,方便管理、精简功能!记录笔记以供以后记忆!
一、工作注意点
1.导入 CocoaAsyncSocket ;
2.新建Model类,设置单例,定义各种成员方法暴露以供外用和自用<connect、login、logout、disconnect、destory等>;
3.字节流设置 :魔数<4字节> + 版本信息<1字节> + 序列化类型<1字节> + 指令<1字节> + body长度<4字节> + body内容;
4.包头恒定为11字节,粘包拆包可以采用分隔符方式,也可以采用以字节流中的body长度+包头长度方式进行划分拆包;
5.代理回调和webSocket区别不是很大<链接成功代理、链接失败代理、发送成功代理、接收消息代理>;
6.发送消息方式:[_socket writeData:data withTimeout:-1 tag:1]
拉取数据方式:[sock readDataWithTimeout:-1 tag:0];
7.相对于webScoket,GCDAsyncSocket需要手动设置拉取数据才能从服务端获取数据<注意拉取数据的代码位置>;
二、核心代码
/// 链接
- (BOOL)connect{
self.isLogined = login_status_ing;
self.isReconnect = YES;
if (_socket.isConnected) {
return NO;
}
if (!_socket) {
_socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
}
NSError *error = nil;
// [_socket connectToHost:@"ts.2uchat.cn" onPort:18089 error:&error];
[_socket connectToHost:@"ip" onPort:端口 error:&error];//161.189.124.112 // 192.168.199.125
if (error) {
MSULog(@"__connect error:%@",error.userInfo);
return NO;
}
return YES;
}
/// 登录
-(void)login{
self.isReconnect = YES;
if(_isLogined == login_status_yes)
return;
if (TU_MyTool.isLogin == NO || TU_MyTool.isKick == YES) {
return;
}
if (![self connect]) {
};
}
/// 退出
-(void)logout{
if(!_isLogined)
return;
self.newMsgCount = 0;
TU_MyTool.lastOfflineTime = [[NSDate date] timeIntervalSince1970];
[self disconnect];
[_roomPool deleteAll];
}
- (void)destory{
if (!_socket.isConnected) {
[self notify];
self.isLogined = login_status_no;
return;
}
[_socket disconnect];
}
/// 已经登录
-(void)doLogin{
NSMutableData *muData = [self publicPamasWithCommand:@"1" toUserId:nil];
NSDictionary *dic = @{@"userId":MY_USER_ID,@"userName":MY_USER_NAME,@"password":[TUMyTool getMD5String:[[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_PASSWORD]],@"deviceType":@"1",@"serialNo":[GSKeyChainDataManager readUUID]};
NSString *jsonStr = [MSUStringTools convertToJsonData:dic];
NSData *aesData = [MSUAesTools msu_aes_encrytGetDataWithStr:jsonStr key:nil];
[muData appendData:[MSUSocketUtils bytesFromUInt32:(uint32_t)aesData.length]];
[muData appendData:aesData];
[self tuSocketModelSendData:muData timeOut:10 tag:1];
}
///公共头
- (NSMutableData *)publicPamasWithCommand:(NSString *)command toUserId:(NSString *)toUserid{
NSMutableData *publicData = [NSMutableData new];
NSData *moShuData = [MSUSocketUtils bytesFromUInt32:0x20170817];
/// 魔数
[publicData appendData:moShuData];
/// 版本号
[publicData appendData:[MSUSocketUtils byteFromUInt8:[@"1" intValue]]];
///序列化类型
[publicData appendData:[MSUSocketUtils byteFromUInt8:[@"1" intValue]]];
[publicData appendData:[MSUSocketUtils byteFromUInt8:[command intValue]]];
// Byte codeKeyByteAry[25]
NSString *from = [MSUSocketUtils hexStringFromData:[MY_USER_ID dataUsingEncoding:NSUTF8StringEncoding]];
NSString *userID = MY_USER_ID;
for (NSInteger i = 0; i < 25-userID.length; i++) {
from = [NSString stringWithFormat:@"%@00",from];
}
NSData *fromData = [MSUSocketUtils dataFromHexString:from];
[publicData appendData:fromData];
NSString *to = [MSUSocketUtils hexStringFromData:[toUserid dataUsingEncoding:NSUTF8StringEncoding]];
for (NSInteger i = 0; i < 25-toUserid.length; i++) {
to = [NSString stringWithFormat:@"%@00",to];
}
NSData *toData = [MSUSocketUtils dataFromHexString:to];
[publicData appendData:toData];
MSULog(@"=======from:%@,to:%@",[MSUSocketUtils hexStringFromData:fromData],[MSUSocketUtils hexStringFromData:toData]);
NSData *platFormData = [MSUSocketUtils byteFromUInt8:[@"1" intValue]];
[publicData appendData:platFormData];
return publicData;
///body
// NSDictionary *dic = @{@"userId":@"10000003",@"userName":@"陈永林",@"password":@"this is password",@"deviceType":@"1",@"SerialNo":@"thisismyserialno"};
// NSString *jsonStr = [self convertToJsonData:dic];
// NSData *aesData = [MSUAesTools msu_aes_encrytGetDataWithStr:jsonStr key:nil];
// [_data appendData:[MSUSocketUtils bytesFromUInt32:(uint32_t)aesData.length]];
//
// [_data appendData:aesData];
///字节数组 、 字节转十六进制字符串 、data 三者的对比
// Byte codeKeyByteAry[aesData.length];
// NSMutableString *muStr = [NSMutableString string];///
//
// NSMutableString *muSixStr = [NSMutableString string];///
//
// for (int i = 0 ; i < aesData.length; i++) {
// NSData *idata = [aesData subdataWithRange:NSMakeRange(i, 1)];
// codeKeyByteAry[i] =((Byte*)[idata bytes])[0];
//
// [muStr appendString:[NSString stringWithFormat:@"%hhu",codeKeyByteAry[i]]];
// // [muSixStr appendString:[self stringWithHexNumber:codeKeyByteAry[i]]];/// 转换成十六进制
// MSULog(@"1111111----%d-----%hhu -----%@ ------%@",i,codeKeyByteAry[i],[self stringWithHexNumber:codeKeyByteAry[i]],idata);
//
// }
// MSULog(@"%@",muSixStr);
}
#pragma mark - Socket Delegate
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
MSULog(@"Socket连接成功:%s",__func__);
self.readBuf = [[NSMutableData alloc] init];
[self doLogin];
[self sendPing];
[sock readDataWithTimeout:-1 tag:0];
}
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
if (err) {
MSULog(@"连接失败--%@",err);
}else{
MSULog(@"正常断开");
}
[_socket disconnect];
self.isLogined = login_status_no;
// if (self.heartTimer) {
// [self.heartTimer invalidate];
// self.heartTimer = nil;
// }
// if ([sock.userData isEqualToString:[NSString stringWithFormat:@"%d",SOCKET_CONNECT_SERVER]])
// {
// //服务器掉线 重新连接
// [self connectToServerWithCommand:@"battery"];
// }else
// {
// return;
// }
}
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag {
MSULog(@"数据发送成功:%s",__func__);
//发送完数据手动读取,-1不设置超时
}
- (void)socket:(GCDAsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag{
MSULog(@"数据接收成功----%@",@"111111111111");
}
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
MSULog(@"数据接收成功----%@",[MSUSocketUtils hexStringFromData:data]);
// NSString *receiverStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSRange range = [receiverStr rangeOfString:@"{"];
// NSString *subStr = [receiverStr substringFromIndex:range.location];
// NSDictionary *dic = [self dictionaryWithJsonString:subStr];
// MSULog(@"接收到的数据----%@",dic);
// MSULog(@"%@",[MSUSocketUtils hexStringFromData:data]);
//
// NSData *moShuData = [data subdataWithRange:NSMakeRange(0, 4)];
// MSULog(@"%@-----魔数:%@",moShuData,[MSUSocketUtils hexStringFromData:moShuData]);
//
// NSData *versionData = [data subdataWithRange:NSMakeRange(4, 1)];
// MSULog(@"%@-----版本:%hhu",versionData,[MSUSocketUtils uint8FromBytes:versionData]);
//
// NSData *typeData = [data subdataWithRange:NSMakeRange(5, 1)];
// MSULog(@"%@-----序列化类型:%hhu",typeData,[MSUSocketUtils uint8FromBytes:typeData]);
///此处采用以字节流中的body长度+包头长度方式进行划分拆包
//将数据存入缓存区
[self.readBuf appendData:data];
while (self.readBuf.length > 11) {
NSData *lenthData = [self.readBuf subdataWithRange:NSMakeRange(7, 4)];
NSUInteger allLength = [MSUSocketUtils uint32FromBytes:lenthData] + 11;///body长度+包头长度
if (self.readBuf.length >= allLength) {
NSMutableData *msgData = [[self.readBuf subdataWithRange:NSMakeRange(0, allLength)] mutableCopy];
[self handelData:msgData withSocket:sock];
_readBuf = [NSMutableData dataWithData:[_readBuf subdataWithRange:NSMakeRange(allLength, _readBuf.length - allLength)]];
} else {
//缓存区内数据包不是完整的,再次从服务器获取数据,中断while循环
[_socket readDataWithTimeout:-1 tag:0];
break;
}
}
[sock readDataWithTimeout:-1 tag:0];
}
- (void)handelData:(NSData *)data withSocket:(GCDAsyncSocket *)sock{
NSData *commandData = [data subdataWithRange:NSMakeRange(6, 1)];
NSString *commandStr = [MSUSocketUtils hexStringFromData:commandData];
// NSData *lenthData = [data subdataWithRange:NSMakeRange(7, 4)];
// MSULog(@"字节流内容%@ ----body长度%u-----指令:%@", [MSUSocketUtils hexStringFromData:data],[MSUSocketUtils uint32FromBytes:lenthData],commandStr);
NSData *bodyData = [data subdataWithRange:NSMakeRange(11, data.length - 11)];
NSString *deStr = [MSUAesTools msu_aes_decrytGetBaseStrWihData:bodyData key:nil];
NSDictionary *resultDic = [MSUStringTools dictionaryWithJsonString:deStr];
MSULog(@"-----body内容:%@",resultDic);
///处理逻辑 略
}