它打开后不能立即写入NSOutputStream吗?

时间:2013-03-19 04:27:53

标签: ios objective-c network-programming

我正在从this教程学习iOS网络编程。我尝试修改代码,以便在连接成功后立即将响应发送到服务器。我改变的代码的唯一部分是在这个函数中。问题是app失速并且没有任何事情发生在[outputStream write:[data bytes] maxLength:[data length]];行上因此NSLog(@"sent test");没有被执行。我做错了什么?

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {       
    NSLog(@"stream event %i", streamEvent);
    switch (streamEvent) {
        case NSStreamEventOpenCompleted:
            NSLog(@"Stream opened");

            //my code
            if (theStream == outputStream) {
                NSLog(@"outputStream");                                
                NSData* data = [NSData dataWithBytes:@"test" length:4];
                [outputStream write:[data bytes] maxLength:[data length]];
                NSLog(@"sent test");
            } //end my code

            break;
        case NSStreamEventHasBytesAvailable:
            if (theStream == inputStream) {
                uint8_t buffer[1024];
                int len;
                while ([inputStream hasBytesAvailable]) {
                    len = [inputStream read:buffer maxLength:sizeof(buffer)];
                    //...
                }
            }
            break;
        case NSStreamEventErrorOccurred:
            NSLog(@"Can not connect to the host!");
            break;
        case NSStreamEventEndEncountered:
            [theStream close];
            [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            [theStream release];
            theStream = nil;
            break;
        default:
            NSLog(@"Unknown event");
    }
}

编辑:此处找到解决方案 How to use NSOutputStream's write message?

1 个答案:

答案 0 :(得分:1)

好的,当我使用原始套接字连接时,我已经使用该代码将数据发送到服务器。它可能对你有所帮助

if (theStream == outputStream) {
        NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];//str is my string to send
        int byteIndex = 0;
        uint8_t *readBytes = (uint8_t *)[data bytes];
        readBytes += byteIndex; // instance variable to move pointer
        int data_len = [data length];
       // NSLog(@"%i",[data length]);
        unsigned int len = ((data_len - byteIndex >= 1024) ?
                            1024 : (data_len-byteIndex));
        uint8_t buf[len];
        (void)memcpy(buf, readBytes, len);
        len = [outputStream write:(const uint8_t *)buf maxLength:len];
        byteIndex += len;

}