我用 Python (Twisted) 编写了一个服务器。我已连接到服务器并将数据发送到服务器,但我没有从服务器获取任何数据并且 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()
我已经尝试了很多并用谷歌搜索,但我没有找到任何解决方案。它正在消磨我的时间,所以如果有人对此进行了研究,请指导我并发布示例代码。提前致谢。