我想使用NSConnection/NSDistributedObject进行进程间通信。我希望客户端能够处理服务器只能偶尔到达的情况。
如何确定向NSConnection发送消息将失败或已失败?当前,如果我的服务器(支持远程对象的进程)死亡,如果客户端向远程对象发送选择器,则客户端将导致崩溃。
理想情况下,我希望为远程对象设置一个包装器,它可以延迟实例化(或恢复)连接,并在连接无法实例化或连接失败的情况下返回默认值。我真的不知道用目标c做这件事的正确方法。
下面是一些表示这个逻辑的伪代码:
if myConnection is null:
instantiate myConnection
if MyConnection is null:
return defaultValue
try
return [myConnection someMethod]
catch
myConnection = null
return defaultValue发布于 2010-04-16 01:13:54
不幸的是,检测连接失败的唯一方法是使用异常处理程序,因为没有可靠的方法“询问”远程对象是否仍然有效。谢天谢地,这很简单:
//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
}发布于 2012-05-12 09:03:59
如果您的服务器正在优雅地退出,我的理解是,当连接关闭时,它将发布一个NSConnectionDidDieNotification,这样您就可以这样注册您的客户端:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectionDidDie:) name:NSConnectionDidDieNotification object:remoteObject];也许您的connectionDidDie:方法可以设置一个布尔变量,您可以在尝试发送消息之前检查该变量。
您的DO可以发布一个通知,说明它已经启动了(虽然我认为也有一些系统消息,但我只是刚刚开始了解DO's),您也可以注册以获得它的启动通知。
我想Rob的回答是一个明确的“通吃”,您不需要担心通知中心没有及时接通服务器。
我在我的第一个DO应用程序中使用了“确实死了”的通知,我希望它能帮助你。
托德。
https://stackoverflow.com/questions/2649059
复制相似问题