2013-08-08 4 views
0

Я написал сервер с Python (Twisted). Я подключился к серверу и отправил данные на сервер, но я не получаю никаких данных с сервера, а NSStreamEventHasBytesAvailable не будет вызван.Не удалось вызвать NSStreamEventHasBytesAvailable

Это, как я подключиться к серверу:

CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"localhost", 3000, &readStream, &writeStream); 
inputStream = (NSInputStream *)readStream; 
outputStream = (NSOutputStream *)writeStream; 
[inputStream setDelegate:self]; 
[outputStream setDelegate:self]; 
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
[inputStream open]; 
[outputStream open]; 

здесь проблема:

-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent 
{ 
    NSString *event; 
    switch (streamEvent) 
    { 
     case NSStreamEventHasBytesAvailable: 
     event = @"NSStreamEventHasBytesAvailable"; 
     if (theStream == inputStream) 
     { 
      uint8_t buffer[1024]; 
      int len; 
      while ([inputStream hasBytesAvailable]) 
      { 
       NSLog(@"input =====%@",inputStream); 

       len = [inputStream read:buffer maxLength:1024]; 
       NSLog(@"len -=======%d",len); 
       if (len > 0) 
       { 
        NSMutableString *output = [[NSMutableString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding]; 
        NSLog(@"Received data--------------------%@", output); 
       } 
      } 
     } 
     break; 
    } 
} 

Это на стороне сервера код:

from twisted.internet.protocol import Factory, Protocol 
from twisted.internet import reactor 

class IphoneChat(Protocol): 
    def connectionMade(self): 
     self.factory.clients.append(self) 
     print "clients are ", self.factory.clients 

    def connectionLost(self, reason): 
     self.factory.clients.remove(self) 

    def dataReceived(self, data): 
     a = data.split(':') 
     print a 
     if len(a) > 1: 
      command = a[0] 
      content = a[1] 

      msg = "" 
      if command == "msg": 
       msg = content 
       print msg 

    def message(self, message): 
     self.transport.write(message + '\n') 

     for c in self.factory.clients: 
      c.message(msg) 

factory = Factory() 
factory.protocol = IphoneChat 
factory.clients = [] 
reactor.listenTCP(650, factory) 
print "Iphone Chat server started" 
reactor.run() 

Я попробовал много и googled, но я не нашел никакого решения. Это убивает мое время, поэтому, если кто-то работал над ним, пожалуйста, помогите мне и отправьте образец кода. Спасибо заранее.

+0

Где вызывается метод 'message'? Это не то, что 'twisted' назовешь правильным? Я бы сказал, что вам может понадобиться вызов функции 'message' в' dataReceived'. – ersran9

+0

, пожалуйста, измените мой код – Goutham

+0

попробуйте сделать 'self.message (msg)' после 'print msg' в вашем блоке' if'. – ersran9

ответ

0

Я ничего не знаю об iphone, но я нахожу что-то не так с вашим сервером. Я бы предпочел написать его как

from twisted.internet.protocol import Factory, Protocol 
from twisted.internet import reactor 

class IphoneChat(Protocol): 
    def connectionMade(self): 
     self.factory.clients.append(self) 
     print "clients are ", self.factory.clients 

    def connectionLost(self, reason): 
     self.factory.clients.remove(self) 

    def dataReceived(self, data): 
     a = data.split(':') 
     print a 
     if len(a) > 1: 
      command = a[0] 
      content = a[1] 

      msg = "" 
      if command == "msg": 
       msg = content 
       self.message(msg) 
       print msg 

    def message(self, message): 
     for c in self.factory.clients: 
      c.transport.write(message + '\n') 

factory = Factory() 
factory.protocol = IphoneChat 
factory.clients = [] 
reactor.listenTCP(650, factory) 
print "Iphone Chat server started" 
reactor.run() 

Когда я протестировал его с помощью telnet-клиента, все получилось хорошо.

Смежные вопросы