Here is the issue. When my app starts up, I connect to server1 at port 5000. I send to data to server1. Server1 sends data back. Server1 close connection. NSStreamEventEndEncountered event occurs for inputStream. Then I connect to server2 at port 5001. I try to send data to server2, but the data ends up going to server1. Somehow the inputStream is connected at port 5001 and my outputStream isconnected at 5000. What am I doing wrong?
- (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");
}
}