NSOutputStream多次写入

时间:2009-04-29 12:16:25

标签: objective-c iphone cocoa-touch sockets

我正在尝试使用NSStream对象打开然后在套接字上写入和读取但我遇到了问题。

我打开它之后,我不知道如何在套接字上写字。

以下是我的表现

1)首先打开套接字:

 NSURL *website = [NSURL URLWithString:urlStr]; 
        if (!website) { 
            NSLog(@"%@ is not a valid URL"); 
            return; 
        } 
        NSHost *host = [NSHost hostWithName:urlStr]; 
        // iStream and oStream are instance variables 
        [NSStream getStreamsToHost:host port:6667 inputStream:&iStream 
                      outputStream:&oStream]; 
        [iStream retain]; 
        [oStream retain]; 
        [iStream setDelegate:self]; 
        [oStream setDelegate:self]; 
        [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] 
                           forMode:NSDefaultRunLoopMode]; 
        [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] 
                           forMode:NSDefaultRunLoopMode]; 
        [iStream open]; 
        [oStream open]; 

2)设置循环:

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{
    NSString *io;

    if (theStream == iStream) io = @">>";
    else io = @"<<";
    NSLog(@"stream : %@",theStream);

    NSString *event;
    switch (streamEvent)
    {
        case NSStreamEventNone:
            event = @"NSStreamEventNone";
            break;
        case NSStreamEventOpenCompleted:
            event = @"NSStreamEventOpenCompleted";
            break;
        case NSStreamEventHasBytesAvailable:{
            event = @"NSStreamEventHasBytesAvailables";
            if (theStream == iStream)
            {
                if(!_data) { 
                    _data = [[NSMutableData data] retain]; 
                } 
                uint8_t buf[1024]; 
                unsigned int len = 0; 
                len = [iStream read:buf maxLength:1024]; 
                NSLog(@"Lenght data read : %d", len);
                if(len) { 
                    NSData * dataReceived= [[NSString stringWithFormat:@"%s\n", (char *)buf] dataUsingEncoding:NSUTF8StringEncoding];
                    NSString *s = [[NSString alloc] initWithData:dataReceived encoding:NSUTF8StringEncoding];
                    NSLog(@"Received _data: \"%@\"\n",s);



                } else { 
                    NSLog(@"nothing to read!"); 
                } 
            }else {
                NSLog(@"Not the good stream");
            }

            break;
        }

        case NSStreamEventHasSpaceAvailable:{
            event = @"NSStreamEventHasSpaceAvailable";
            if (theStream == oStream )
            {
                if(isConnexionCommandSent == NO){
                    [self sendCommand:@"My connection command"];    
                    isConnexionCommandSent = YES;
                }

            }

            break;
        }

        case NSStreamEventErrorOccurred:
            event = @"NSStreamEventErrorOccurred";
            NSError *theError = [theStream streamError]; 
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[theError localizedDescription]
                                                           delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
            [alert show];
            [alert release];
            break;
        case NSStreamEventEndEncountered:
            event = @"NSStreamEventEndEncountered";

            break;
        default:
            event = @"** Unknown";
    }

    NSLog(@"%@ : %@", io, event);
}

3)然后我有一个按下按钮时调用的功能

- (IBAction)join:(id)sender{
    if([oStream hasSpaceAvailable]){
        NSLog(@"iStream Status : %d",[iStream streamStatus]);
        NSLog(@"oStream Status : %d",[oStream streamStatus]);
        [self sendCommand:@"join"];

    }else{
        NSLog(@"Error command can't be sent");      
    }
}

-(void) sendCommand:(NSString *) command{
    NSLog(@"space : %d",[oStream hasSpaceAvailable]);
    if ([oStream hasSpaceAvailable])
    {
        NSLog(@"Command writen : %s\n",[command cStringUsingEncoding:NSASCIIStringEncoding]);
        NSInteger i=[oStream write:(const uint8_t *)[command cStringUsingEncoding:NSASCIIStringEncoding] maxLength:(NSInteger)[command lengthOfBytesUsingEncoding:NSASCIIStringEncoding]];
        if (i<0)
        {
            NSLog(@"erreur lors de l'envoi, status:%i, erreur:%@", [oStream streamStatus], [oStream streamError]);
        }
        isReadyToSend = NO;
    }

    else
    {
        NSLog(@"impossible d'envoyer, status:%i, erreur:%@", [oStream streamStatus], [oStream streamError]);
    }
}

但问题是,当调用函数join时,一切都很顺利,但服务器什么都没收到......

开启

NSInteger i=[oStream write:(const uint8_t *)[command cStringUsingEncoding:NSASCIIStringEncoding] maxLength:(NSInteger)[command lengthOfBytesUsingEncoding:NSASCIIStringEncoding]];

我是&gt; 0,所以我认为写作进展顺利,但在服务器上没有收到任何内容......我不知道为什么......

你能帮帮我吗?

2 个答案:

答案 0 :(得分:0)

嘿@Ptitaw见this post。我相信你可以找到你的答案和一种更简单的方法来连接并自动访问所有事件(阅读,写作等......) 希望我能帮忙:)。

答案 1 :(得分:0)

答案非常晚,但对于有类似问题的人可能会有所帮助。

我认为这可能是由于数据编码机制造成的。您的服务器可能正在使用UTF-8编码,并且您使用NSASCIIStringEncoding发送数据。试试这个:

NSInteger i=[oStream write:(const uint8_t *)[command cStringUsingEncoding:NSUTF8StringEncoding] maxLength:(NSInteger)[command lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];