iOS-Socket(CocoaAsyncSocket)用16進(jìn)制接收數(shù)據(jù)

第三方框架直接podfile導(dǎo)入GCDAsyncSocket。
#import <GCDAsyncSocket.h>
遵循<GCDAsyncSocketDelegate>這個(gè)第三方框架代理協(xié)議
// 定義客戶端socket
@property (strong, nonatomic) GCDAsyncSocket *clientSocket;
// 1.初始化GCDAsyncSocket
    self.clientSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
//終端打開IP和端口 nc -lk xxxx  xxxx為端口號(hào)
//第一參數(shù),IP地址
//第二參數(shù),端口號(hào)
// 2.鏈接服務(wù)器
   // withTimeout -1 : 無(wú)窮大,一直等
    [self.clientSocket connectToHost:self.addressTF.text onPort:self.portTF.text.integerValue viaInterface:nil withTimeout:-1 error:nil];
//3.發(fā)送消息給服務(wù)器
    NSMutableArray *arrayMsg = [[NSMutableArray alloc]init];
    //    ==msg head id==
    [arrayMsg addObject:@(0x21)];
    [arrayMsg addObject:@(0x00)];
    [arrayMsg addObject:@(0x00)];
    [arrayMsg addObject:@(0x00)];
    //    ==msg head ack==
    [arrayMsg addObject:@(0x00)];
    //    ==msg head dir==
    [arrayMsg addObject:@(0x01)];
    [arrayMsg addObject:@(0x00)];
    [arrayMsg addObject:@(0x00)];
    [arrayMsg addObject:@(0x00)];
    //    ==cmd_Id==
    [arrayMsg addObject:@(0x07)];
    [arrayMsg addObject:@(0x00)];
    
    [arrayMsg addObject:@(0x00)];
    [arrayMsg addObject:@(0x00)];
    [arrayMsg addObject:@(0x0E)];
    [arrayMsg addObject:@(0x00)];
    //    ==cmd_Datalen==
    [arrayMsg addObject:@(0x01)];
    [arrayMsg addObject:@(0x00)];
    //    ==cmd_DataSum==
    [arrayMsg addObject:@(0x01)];
    [arrayMsg addObject:@(0x00)];
    //    ==cmd_Data==
    [arrayMsg addObject:@(0x01)];
    Byte socketShake[20];
    for (int i = 0; i<[arrayMsg count]; i++) {
        socketShake[i] = (Byte)[[arrayMsg objectAtIndex:i] intValue];
    }
    NSData *shakeData = [NSData dataWithBytes:socketShake length:[arrayMsg count]];
    // withTimeout -1 : 無(wú)窮大,一直等
    // tag : 消息標(biāo)記
    [self.clientSocket writeData:shakeData withTimeout:-1 tag:0];

#pragma mark - GCDAsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    [self showMessageWithStr:@"鏈接成功"];
    NSLog(@"鏈接成功");
    [self showMessageWithStr:[NSString stringWithFormat:@"服務(wù)器IP: %@", host]];
    [self.clientSocket readDataWithTimeout:-1 tag:0];
}
// 收到消息
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSLog(@"收到消息");
    NSString *str = [self HexStringWithData:data];
    [self showMessageWithStr:[NSString stringWithFormat:@"收到消息:%@",str]];
    NSLog(@"收到消息:str = %@",str);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

// 信息展示
- (void)showMessageWithStr:(NSString *)str {
    self.showMessageTF.text = [self.showMessageTF.text stringByAppendingFormat:@"%@\n", str];
}

// 鏈接失敗
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    NSLog(@"鏈接失敗 \t,err = %@,%ld",err.domain,(long)err.code);
}

//data轉(zhuǎn)為十六進(jìn)制字符串
-(NSString *)HexStringWithData:(NSData *)data{
    Byte *bytes = (Byte *)[data bytes];
    NSString *hexStr=@"";
    for(int i=0;i<[data length];i++) {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16進(jìn)制數(shù)
        if([newHexStr length]==1){
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        }
        else{
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
        }
    }
    hexStr = [hexStr uppercaseString];
    return hexStr;
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容