在iOS中保持套接字连接存活 [英] Keeping a socket connection alive in iOS

查看:155
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆