3

我正在从教程中学习 iOS 网络编程。我尝试修改代码,以便在连接成功后立即向服务器发送响应。我更改的代码的唯一部分是在这个函数中。问题是应用程序停止并且行上没有任何反应[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");
    }
}

编辑:在此处找到解决方案 如何使用 NSOutputStream 的写入消息?

4

1 回答 1

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;

}
于 2013-03-19T12:35:19.750 回答