iPhone:使用 NSStream 捕获连接错误
我编写了一个程序,使用 Apple 流编程指南中概述的 NSStream 协议连接到给定 IP 上的服务器。数据的连接和传输工作完美,但是如果用户指定了错误的 IP 并且程序尝试打开流,则会导致程序无响应。
根据我的阅读,handleEvent 方法检测到流错误,但是当我检查 eventCode == NSStreamEventErrorOccurred 的条件时,似乎什么也没有发生。我的连接代码如下:
NSString *hostString = ipField.text;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)hostString, 10001, &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];
如果无法建立连接,是否知道如何指定超时值或允许按钮触发流的关闭?
I have written a program that connects to a server on a given IP using the NSStream protocol outlined in Apple's stream programming guide. The connection and transfer of data works flawlessly, however if the user specifies the wrong IP and the program attempts to open the streams it results in the program becoming unresponsive.
From what I have read, the handleEvent method detects stream errors, however when I check for the condition that eventCode == NSStreamEventErrorOccurred, nothing seems to happen. My connect code is as follows:
NSString *hostString = ipField.text;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)hostString, 10001, &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];
Any idea as to how I can specify a timeout value or allow for a button to trigger the closing of the streams if a connection cannot be made?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
NSTimer
。在你的 .h 中:
在你的 .m 中:
Use an
NSTimer
.In your .h:
In your .m: