开发者

Async CFStream networking with runloop

开发者 https://www.devze.com 2023-01-26 07:21 出处:网络
I am trying to implement async tcp networking with runloop. currently I manage to connect, but when I try to send something I get that -1 bytes have been written - but CFWriteStreamCopyError returns n

I am trying to implement async tcp networking with runloop. currently I manage to connect, but when I try to send something I get that -1 bytes have been written - but CFWriteStreamCopyError returns null.

code sample below, first function connects, second send a simple message. any help will be appreciated, including random bug spotting (I am new to objective-c and to iphone development in general).

struct header
{
    uint32_t length;
    uint32_t type;
} header;

- (void) connect
{
    NSLog(@"Attempting to (re)connect to %@:%d", m_host, m_port);
    while(TRUE)
    {
        CFHostRef host = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)m_host);
        if (!host)
        {
            NSLog(@"Error resolving host %@", m_host);
            [NSThread sleepForTimeInterval:5.0];
            continue;
        }
        CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, host , m_port, &m_in, &m_out);
        CFRelease(host);

        if (!m_in)
        {
            NSLog(@"Error");
        }

        CFStreamClientContext context = {0, self,nil,nil,nil};

        if (CFReadStreamSetClient(m_in, kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkReadEvent, &context))
        {
            CFReadStreamScheduleWithRunLoop(m_in, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
        }

        if (CFWriteStreamSetClient(m_out, kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, networkWriteEvent, &context))
        {
            CFWriteStreamScheduleWithRunLoop(m_out, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
        }


        BOOL success = CFReadStreamOpen(m_in);
        CFErrorRef error = CFReadStreamCopyError(m_in);
        if (!success || (error && CFErrorGetCode(error) != 0))
        {
            NSLog(@"Connect error %s : %d", CFErrorGetDomain(error), CFErrorGetCo开发者_JS百科de(error));
            [NSThread sleepForTimeInterval:5.0];
        }
        else 
        {
            NSLog(@"Connected");
            break;
        }
    }


    [self startSession];
}

- (void) startSession
{
    struct header hh;
    hh.type = RTR_CREATE_SESSION;
    hh.length = 0;
    CFIndex res = CFWriteStreamWrite(self.m_out, (const UInt8*)&hh, sizeof(hh));
    NSLog(@"Written %d", res);

    CFErrorRef error = CFWriteStreamCopyError(self.m_out);
    if (error)
    {
        NSLog(@"Read error %s : %d", CFErrorGetDomain(error), CFErrorGetCode(error));
        CFRelease(error);
    }
}


figured it out, I forgot to open the write stream as well:

CFWriteStreamOpen(m_out);
0

精彩评论

暂无评论...
验证码 换一张
取 消