检测/修复NSConnection连接失败
-
27-09-2019 - |
题
我想用NSConnection连接/ NSDistributedObject用于进程间通信。我想客户端能够处理其中服务器只是偶尔可到达的情况。
我怎样才能确定是否将消息发送到NSConnection连接失败或已经失败了?目前,如果我的服务器(即已经贩卖远程对象的处理)的模具中,客户端会的崩溃如果它发送一个选择器到远程对象。
理想情况下,我想对远程对象,可以懒惰地实例化(或重新实例)的连接的封装器,并且在该连接不能被实例化,或连接失败的情况下返回默认值。我真的不知道正确的方式来做到这一点使用Objective C的。
下面是表示此逻辑的伪代码:
if myConnection is null:
instantiate myConnection
if MyConnection is null:
return defaultValue
try
return [myConnection someMethod]
catch
myConnection = null
return defaultValue
解决方案
不幸的是,以检测连接故障的唯一方法是使用一个异常处理程序,如存在于“询问”远程对象如果连接仍然是有效的没有可靠的方法。幸运的是,这是简单的:
//get the distributed object
id <YourDOProtocol> remoteObject = (id <YourDOProtocol>)[NSConnection rootProxyForConnectionWithRegisteredName:@"YourRegisteredName" host:yourHost];
//call a method on the distributed object
@try
{
NSString* response = [remoteObject responseMethod];
//do something with response
}
@catch(NSException* e)
{
//the receiver is invalid, which occurs if the connection cannot be made
//handle error here
}
其他提示
如果你的服务器是正常在quiting然后,我的理解,它会发布一个NSConnectionDidDieNotification
,因为它的连接关闭,所以你可以注册你的客户是这样的:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectionDidDie:) name:NSConnectionDidDieNotification object:remoteObject];
也许你connectionDidDie:
method可以设置一个布尔VAR,你可以检查试图发送消息之前。
您DO可以张贴的通知说,它的开始(虽然我觉得也有该系统的信息,但我刚开始学习DO的),你可以同样注册通知它的启动。
我想罗布的回答是明确的“包罗万象”,你就不需要了解具有不经过及时的服务器得到了通知中心的担心。
我一直在使用“的确死”通知它在我的第一个DO应用程序,我希望它可以帮助你。
托德。
不隶属于 StackOverflow