在 iOS 中保持套接字连接处于活动状态 [英] Keeping a socket connection alive in iOS
问题描述
我用 Objective-C 编写了以下代码,用于将数据写入套接字.服务器在 Ubuntu 上运行 node.js:
I have the following code written in Objective-C that writes data to a socket. The server is running node.js on top of Ubuntu:
NSString *url = @"anIPAddress";
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)url, 9000, &readStream, &writeStream);
self.inputStream = (NSInputStream *)readStream;
self.outputStream = (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];
我能够连接到服务器并发送信息.但是我注意到几分钟后连接超时(我想是 5 分钟左右?).我怎样才能保持这种联系?我知道存在断开连接,因为如果我在终端下连接到服务器,也会发生同样的事情,我必须保持该连接处于活动状态.我想我的代码中也会发生同样的事情.感谢您的帮助!
I am able to connect to the server and send information. However I noticed the connection times out after a few minutes (I think 5 minutes or so?). How can I keep this connection alive? I know there is a disconnect because the same thing happens if I connect to the server under Terminal, I have to keep that connection alive. I imagine the same thing is happening in my code. Thanks for your help!
推荐答案
我找到了如何做到这一点.由于服务器运行的是 node.js,所以我使用了
I found how to do this. Since the server is running node.js, I used
socket.setKeepAlive(true, 2000);
以这种方式节点保持每个套接字打开.默认值为 false,所以这就是超时的原因.我希望这对其他人有用.感谢您的回复,我认为保持心跳(保持活动状态)也是一个好主意,但使用这种本地方法节点会处理它.
And in this way node keeps each socket open. The default is false, so this is why it was timing out. I hope this is useful to other people. Thank your for your responses, I think keeping a heartbeat (keep-alive) is also a good idea, but with this native approach node takes care of it.
这篇关于在 iOS 中保持套接字连接处于活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!