我正在使用 CFStream 构建一个 IOS 套接字客户端。我已经设法连接到我的测试服务器并从中接收消息。问题是如果客户端发送消息服务器无法接收它,然后客户端没有收到来自服务器的任何消息。我的代码如下。有什么问题?
- (void)initCommunicationWithAddress:(NSString*) address withPort:(int) port
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)address, port, &readStream, &writeStream);
self.inputStream = (__bridge_transfer NSInputStream *)readStream;
self.outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream open];
[self.outputStream open];
NSLog(@"Socket Init: %@", @"");
}
- (void)sendMessage:(NSString*)msg
{
msg = @"hello";
NSLog(@"SendMessage: %@", msg);
NSData *data = [[NSData alloc] initWithData:[msg dataUsingEncoding:NSASCIIStringEncoding]];
[self.outputStream write:[data bytes] maxLength:[data length]];
}
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
switch (streamEvent) {
case NSStreamEventOpenCompleted:
[self streamOpened];
break;
case NSStreamEventHasBytesAvailable:
NSLog(@"Stream Bytes Available:%@", @"");
if (theStream == self.inputStream) {
NSMutableData* data = [NSMutableData data];
uint8_t buffer[1024];
int len;
int bytesRead = 0;
while ([self.inputStream hasBytesAvailable])
{
len = [self.inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
[data appendBytes:(const void *)buffer length:len];
bytesRead = bytesRead + len;
}
}
NSString* output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (nil != output) {
[self HandleServerMessage: output];
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(@"Stream Error:%@", @"");
[self streamError];
break;
case NSStreamEventEndEncountered:
NSLog(@"Stream Event End:%@", @"");
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self streamEnd];
break;
default:
NSLog(@"Unknown event");
}
}