0
這是問題。當我的應用程序啓動時,我在端口5000連接到server1。我發送數據到server1。 Server1發回數據。 Server1關閉連接。 inputStream發生NSStreamEventEndEncountered事件。然後我在端口5001連接到server2。我嘗試將數據發送到server2,但數據最終到達server1。不知怎的,inputStream在端口5001連接,我的outputStream在5000連接。我做錯了什麼?NSOutputStream不能關閉?
- (void) initNetworkCommunication: (uint32_t)port {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"localhost", port, &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) onClientConnectionLost {
if (atServer1 == YES) {
atServer1 = NO;
[self initNetworkCommunication: 5001];
}
if (atServer1 == NO) {
atServer1 = YES;
[self initNetworkCommunication: 5000];
}
}
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
//handle packets...
}
break;
case NSStreamEventErrorOccurred:
NSLog(@"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
if (theStream == inputStream) {
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[theStream release];
theStream = nil;
[outputStream close];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream release];
outputStream = nil;
[self onClientConnectionLost];
}
break;
default:
NSLog(@"Unknown event");
}
}