備注:項(xiàng)目中需要放棄掉XMPP框架虱肄,自定義Socket長(zhǎng)鏈接去進(jìn)行通信的實(shí)現(xiàn),方便管理交煞、精簡(jiǎn)功能咏窿!記錄筆記以供以后記憶!
一素征、工作注意點(diǎn)
1.導(dǎo)入 CocoaAsyncSocket 集嵌;
2.新建Model類,設(shè)置單例御毅,定義各種成員方法暴露以供外用和自用<connect根欧、login、logout端蛆、disconnect凤粗、destory等>;
3.字節(jié)流設(shè)置 :魔數(shù)<4字節(jié)> + 版本信息<1字節(jié)> + 序列化類型<1字節(jié)> + 指令<1字節(jié)> + body長(zhǎng)度<4字節(jié)> + body內(nèi)容今豆;
4.包頭恒定為11字節(jié)嫌拣,粘包拆包可以采用分隔符方式柔袁,也可以采用以字節(jié)流中的body長(zhǎng)度+包頭長(zhǎng)度方式進(jìn)行劃分拆包;
5.代理回調(diào)和webSocket區(qū)別不是很大<鏈接成功代理异逐、鏈接失敗代理捶索、發(fā)送成功代理、接收消息代理>灰瞻;
6.發(fā)送消息方式:[_socket writeData:data withTimeout:-1 tag:1]
拉取數(shù)據(jù)方式:[sock readDataWithTimeout:-1 tag:0];
7.相對(duì)于webScoket腥例,GCDAsyncSocket需要手動(dòng)設(shè)置拉取數(shù)據(jù)才能從服務(wù)端獲取數(shù)據(jù)<注意拉取數(shù)據(jù)的代碼位置>;
二酝润、核心代碼
/// 鏈接
- (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];
}
/// 已經(jīng)登錄
-(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];
/// 魔數(shù)
[publicData appendData:moShuData];
/// 版本號(hào)
[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];
///字節(jié)數(shù)組 燎竖、 字節(jié)轉(zhuǎn)十六進(jìn)制字符串 、data 三者的對(duì)比
// 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]]];/// 轉(zhuǎn)換成十六進(jìn)制
// 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(@"正常斷開(kāi)");
}
[_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]])
// {
// //服務(wù)器掉線 重新連接
// [self connectToServerWithCommand:@"battery"];
// }else
// {
// return;
// }
}
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag {
MSULog(@"數(shù)據(jù)發(fā)送成功:%s",__func__);
//發(fā)送完數(shù)據(jù)手動(dòng)讀取袍祖,-1不設(shè)置超時(shí)
}
- (void)socket:(GCDAsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag{
MSULog(@"數(shù)據(jù)接收成功----%@",@"111111111111");
}
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
MSULog(@"數(shù)據(jù)接收成功----%@",[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(@"接收到的數(shù)據(jù)----%@",dic);
// MSULog(@"%@",[MSUSocketUtils hexStringFromData:data]);
//
// NSData *moShuData = [data subdataWithRange:NSMakeRange(0, 4)];
// MSULog(@"%@-----魔數(shù):%@",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]);
///此處采用以字節(jié)流中的body長(zhǎng)度+包頭長(zhǎng)度方式進(jìn)行劃分拆包
//將數(shù)據(jù)存入緩存區(qū)
[self.readBuf appendData:data];
while (self.readBuf.length > 11) {
NSData *lenthData = [self.readBuf subdataWithRange:NSMakeRange(7, 4)];
NSUInteger allLength = [MSUSocketUtils uint32FromBytes:lenthData] + 11;///body長(zhǎng)度+包頭長(zhǎng)度
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 {
//緩存區(qū)內(nèi)數(shù)據(jù)包不是完整的底瓣,再次從服務(wù)器獲取數(shù)據(jù),中斷while循環(huán)
[_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(@"字節(jié)流內(nèi)容%@ ----body長(zhǎng)度%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內(nèi)容:%@",resultDic);
///處理邏輯 略
}