ios - 连接socket服务器后会自动断开
PHP中文网
PHP中文网 2017-04-18 09:51:52
0
2
518

业务要求连接socket服务器,然后向服务器发送一条指令,后接收服务器返回的数据。现在的问题是我连上服务器并向服务器发送指令后,socket连接会自己断开(执行了socketDidDisconnect这个回掉方法),收不到服务器返回的数据,请问这是什么问题?
比较奇怪的是,在socketDidDisconnect这个方法里打印socket,却是null,err也没有

- (void)connect
{
    dispatch_queue_t mainQ = dispatch_get_main_queue();
    GCDAsyncSocket *asyncSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:mainQ];
   
    
    NSString *host = @"xxx";
    uint16_t port = xxx;
    
    MYLog(@"connecting");
    NSError *error = nil;
    if (![asyncSocket connectToHost:host onPort:port error:&error]) {
        MYLog(@"oops");
    }
}


- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    MYLog(@"connected");
    Byte byte[] = {0x10, 0x03, -1, 0x00, 0x10, 0x03};
    NSData *data = [[NSData alloc]initWithBytes:byte length:sizeof(byte)];
    MYLog(@"data:%@",data);
   [sock writeData:data withTimeout:-1 tag:1];
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
    MYLog(@"written tag:%ld",tag);
    [sock readDataWithTimeout:-1 tag:1];
}


- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    MYLog(@"read data");
    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    MYLog(@"disconnect err:%@ ",err.localizedDescription,);
}
PHP中文网
PHP中文网

认证高级PHP讲师

모든 응답(2)
黄舟

해결되었습니다. asyncSocket을 속성으로 설정하세요....
@property (strong, nonatomic) GCDAsyncSocket *asyncSocket;

伊谢尔伦

socketDidDisconnect에서 반환된 오류는 무엇입니까

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!