2013-10-12 15 views
7

Sto creando un'applicazione di chat utilizzando NSStream che si collegano a un semplice server socket c. Lo stream si collega correttamente e invia i dati, ma non è in grado di ricevere i dati. Qui è la mia classe Socket che utilizza NSStreams:NSStream Impossibile ricevere dati

socket.h

@interface Socket : NSObject <NSStreamDelegate> 

- (void)connectToServerWithIP:(NSString *)ip andPort:(int)port; 
- (NSString *)sendMessage:(NSString *)outgoingMessage; 

@end 

Socket.m

#import "Socket.h" 

@interface Socket() 

@property (strong, nonatomic) NSInputStream *inputStream; 
@property (strong, nonatomic) NSOutputStream *outputStream; 
@property (strong, nonatomic) NSString *output; 

@end 

@implementation Socket 

@synthesize inputStream; 
@synthesize outputStream; 
@synthesize output; 

- (void)connectToServerWithIP:(NSString *)ip andPort:(int)port 
{ 
    CFReadStreamRef readStream; 
    CFWriteStreamRef writeStream; 
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)ip, port, &readStream, &writeStream); 
    inputStream = (__bridge_transfer NSInputStream *)readStream; 
    outputStream = (__bridge_transfer NSOutputStream *)writeStream; 
    [inputStream setDelegate:self]; 
    [outputStream setDelegate:self]; 
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
    [inputStream open]; 
    [outputStream open]; 
} 

- (NSString *)sendMessage:(NSString *)outgoingMessage 
{ 
    NSData *messageData = [outgoingMessage dataUsingEncoding:NSUTF8StringEncoding]; 
    const void *bytes = [messageData bytes]; 
    uint8_t *uint8_t_message = (uint8_t*)bytes; 
    [outputStream write:uint8_t_message maxLength:strlen([outgoingMessage cStringUsingEncoding:[NSString defaultCStringEncoding]])]; 
    while (![inputStream hasBytesAvailable]) { 
     usleep(10); 
    } 
    uint8_t buffer[1024]; 
    [inputStream read:buffer maxLength:1023]; 
    NSString *outputString = [NSString stringWithUTF8String:(char *)buffer]; 
    return outputString; 
} 

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent { 
    NSLog(@"Stream Event: %lu", streamEvent); 

    switch (streamEvent) { 
     case NSStreamEventOpenCompleted: 
      NSLog(@"Stream opened"); 
      break; 
     case NSStreamEventHasBytesAvailable: 
      if (theStream == inputStream) { 
       uint8_t buffer[1024]; 
       long len; 
       while ([inputStream hasBytesAvailable]) { 
        len = [inputStream read:buffer maxLength:sizeof(buffer)]; 
        if (len > 0) { 
         output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding]; 
         if (output) { 
          NSLog(@"Data: %@", output); 
         } 
        } 
       } 
      } 
      break; 
     case NSStreamEventErrorOccurred: 
      NSLog(@"Can not connect to the host!"); 
      break; 
     case NSStreamEventEndEncountered: 
      [theStream close]; 
      [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
      theStream = nil; 
      break; 
     default: 
      NSLog(@"Unknown event"); 
    } 
} 

@end 

ChatViewController.m

// 
// ChatViewController.m 
// Chat 
// 
// Created by James Pickering on 10/5/13. 
// Copyright (c) 2013 James Pickering. All rights reserved. 
// 

#import "ChatViewController.h" 
#import "LoginViewController.h" 
#import "StatusView.h" 

@interface ChatViewController() 

@property (strong) IBOutlet NSTableView *people; 
@property (strong) IBOutlet NSTextField *message; 
@property (strong) IBOutlet NSButton *send; 
@property (strong) IBOutlet NSButton *loginButton; 
@property (strong) IBOutlet NSButton *settingsButton; 
@property (strong) IBOutlet NSButton *panicButton; 

@property (strong, nonatomic) NSString *recievedText; 
@property (strong, nonatomic) NSMutableArray *tableData; 
@property (strong, nonatomic) NSInputStream *inputStream; 
@property (strong, nonatomic) NSOutputStream *outputStream; 


- (void)openChat:(id)sender; 

- (IBAction)panic:(id)sender; 
- (IBAction)loginToChat:(id)sender; 

@end 

@implementation ChatViewController 

@synthesize sock; 
@synthesize recievedText; 
@synthesize inputStream; 
@synthesize outputStream; 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     self.isLoggedIn = FALSE; 
     sock = [[Socket alloc] init]; 
     [sock connectToServerWithIP:@"127.0.0.1" andPort:5001]; 
     //[self updateUI]; 
    } 
    return self; 
} 

- (void)updateUI 
{ 
    if (self.isLoggedIn) { 
     recievedText = [sock sendMessage:@"getPeople"]; 
     self.tableData = [[NSMutableArray alloc] initWithArray:[recievedText componentsSeparatedByString:@";"]]; 
     NSLog(@"%@", self.tableData); 
     [self.people reloadData]; 
    } 
} 

- (void)openChat:(id)sender 
{ 
    NSLog(@"tru"); 
} 

- (IBAction)panic:(id)sender { 

} 

- (IBAction)loginToChat:(id)sender { 
    NSLog(@"Called"); 
    if (self.loginPopover == nil) { 
     NSLog(@"Login Popover is nil"); 
     self.loginPopover = [[NSPopover alloc] init]; 
     self.loginPopover.contentViewController = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil]; 
    } 
    if (!self.loginPopover.isShown) { 
     NSLog(@"Login Popover is opening"); 
     [self.loginButton setTitle:@"Cancel"]; 
     [self.settingsButton setEnabled:NO]; 
     [self.send setEnabled:NO]; 
     [self.message setEnabled:NO]; 
     [self.loginPopover showRelativeToRect:self.loginButton.frame ofView:self.view preferredEdge:NSMinYEdge]; 
    } 
    else { 
     NSLog(@"Login Popover is closing"); 
     [self.loginButton setTitle:@"Login"]; 
     [self.settingsButton setEnabled:YES]; 
     [self.send setEnabled:YES]; 
     [self.message setEnabled:YES]; 
     [self.loginPopover close]; 
    } 
} 

- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView 
{ 
    return [self.tableData count]; 
} 

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex 
{ 
    return [self.tableData objectAtIndex:rowIndex]; 
} 

- (BOOL)canBecomeKeyWindow 
{ 
    return YES; 
} 

- (BOOL)loginWithUsername:(NSString *)username andPassword:(NSString *)password 
{ 
    // Error happens here 

    recievedText = [sock sendMessage:@"login"]; 
    if ([recievedText isEqualToString:@"roger"]) { 
     recievedText = [sock sendMessage:[NSString stringWithFormat:@"%@;%@", username, password]]; 
     if ([recievedText isEqualToString:@"access granted"]) { 
      return YES; 
     } 
     else { 
      return NO; 
     } 
    } 
    else { 
     return NO; 
    } 
} 

@end 

Il problema è che si blocca su questa riga di codice per sempre: while (![inputStream hasBytesAvailable]) {}, ma non ho idea del perché. Il server dovrebbe inviare un messaggio indietro.

+0

Sto affrontando lo stesso problema ... qualsiasi soluzione? –

risposta

4

Quindi, guardando il tuo NSStreamDelegate, sembra che tu non abbia implementato tutti i casi per tale istruzione switch. Recentemente ho scritto un client IRC per OS X che utilizza NSStream e NSStreamDelegate in un modo molto simile, e sono abbastanza sicuro che il compilatore dovrebbe lamentarsi quando non hai controllato tutti i casi lì.

Guardando indietro al some of my code sembra che si dovrebbe essere il controllo per i casi

  • NSStreamEventHasSpaceAvailable
  • NSStreamEventOpenCompleted
  • NSStreamEventHasBytesAvailable
  • NSStreamEventEndEncountered
  • NSStreamEventErrorOccurred

Quindi il caso che non hai controllato è NSStreamEventHasSpaceAvailable, che è quando puoi iniziare a scrivere sul tuo stream.

edit: Lettura di nuovo il codice, vedo nella tua sendMessage azione che si sta utilizzando l'oggetto outputStream invece del delegato di scrivere, e poi fare il lavoro da soli a leggere dalla inputStream. Penso che probabilmente vorrai usare il delegato e non leggere mai direttamente dal tuo inputstream perché semplificherà enormemente il modo in cui il tuo codice riceve i dati dalla rete. Da quello che ho capito, NSStream è lì per fornire un piccolo strato di astrazione attorno al fatto che i dati vengono memorizzati nella rete in modo da non dover fare cose come chiamare usleep mentre il flusso di input non ha byte disponibili per la lettura.

edit2: Ho letto il tuo aggiornamento sul tuo codice che non ha mai superato while (![inputStream hasBytesAvailable]) e sembra abbastanza chiaro che il problema è che non stai utilizzando i tuoi stream correttamente. Per come la vedo io, il modo migliore per usare NSStream è rispondere agli eventi, usando il suo metodo handleEvent:(NSStreamEvent) event, e mai direttamente dire di scrivere byte, o di dormire fino a quando non sono disponibili byte.

Nel codice che ho collegato a voi, ho un readDelegate e un writeDelegate che entrambi gestiscono NSStreams, si potrebbe voler dare un'occhiata a come uso il mio writeDelegate here. Fondamentalmente ho un metodo, addCommand:(NSString *) command che mette una stringa per scrivere nello stream in una coda, e quindi quando il mio delegato di streaming può scrivere byte (NSStreamEventHasSpaceAvailable), scrivo quanti più byte possibile. Spero che aiuti!

+0

Grazie per la risposta. Il motivo per cui ho il flusso di input è perché non voglio che ritorni nullo se non ci sono byte disponibili, quindi faccio un ciclo finché non ha qualcosa da restituire. La cosa divertente è che quando prendo la riga 'if (isLoggedIn)' del codice, il codice nell'interfaccia utente di aggiornamento funziona perfettamente, sia per l'invio che per la ricezione dei dati. Sto esaminando il tuo suggerimento e spero che funzioni. – jamespick

+0

Non c'è nulla 'NSStreamHasSpaceAvailable' invece c'è 'NSStreamEventHasSpaceAvailable'. –

Problemi correlati