gpt4 book ai didi

ios - NSOutputStream 无法关闭?

转载 作者:行者123 更新时间:2023-11-28 22:37:37 47 4
gpt4 key购买 nike

问题来了。当我的应用程序启动时,我在端口 5000 连接到 server1。我将数据发送到 server1。 Server1 发回数据。 Server1 关闭连接。 InputStream 发生 NSStreamEventEndEncountered 事件。然后我在端口 5001 连接到 server2。我尝试将数据发送到 server2,但数据最终到达了 server1。输入流以某种方式连接到端口 5001,而我的输出流连接到端口 5000。我做错了什么?

- (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");
}
}

最佳答案

- (void) onClientConnectionLost {
if (atServer1 == YES) {
atServer1 = NO;
[self initNetworkCommunication: 5001];
}
else if (atServer1 == NO) {
atServer1 = YES;
[self initNetworkCommunication: 5000];
}

在您的旧代码上...当 atServer1 = YES 时,它将执行第一个 if 语句...将 atServer1 设置为 NO...所以第二个 if 语句为 TRUE...所以它也会执行...

关于ios - NSOutputStream 无法关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15490159/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com