How do I read data using CocoaAsyncSocket?

前端 未结 1 845
时光说笑
时光说笑 2021-01-06 07:49

I have created a TCP Socket connection in my appDelegate didFinishLaunchingWithOptions method. That was the easy part, and I have successfully connect

相关标签:
1条回答
  • 2021-01-06 08:41

    This should work:

    - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
    {
        NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length])];
        NSString *msg = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
        if(msg)
        {
            NSLog(@"RX:%@",msg);
        }
    }
    

    You should also implement some other delegate methods, for example:

    - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
    {
        NSLog(@"error - disconnecting");
        //you'd probably want to start reconnecting procedure here...
    }
    
    - (void)onSocketDidDisconnect:(AsyncSocket *)sock
    {
        NSLog(@"disconnected");
    }
    
    - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
    {
        NSLog(@"connected");
    }
    

    EDIT: if memory serves me right there is some documentation and also some examples available with the library.

    0 讨论(0)
提交回复
热议问题