2

我想使用 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
4

2 回答 2

2

不幸的是,检测连接失败的唯一方法是使用异常处理程序,因为没有可靠的方法来“询问”远程对象是否仍然有效。幸运的是,这很简单:

//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
}
于 2010-04-16T01:13:54.267 回答
0

如果您的服务器正常退出,我的理解是,它会在NSConnectionDidDieNotification连接关闭时发布一个,因此您可以像这样注册您的客户端:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectionDidDie:) name:NSConnectionDidDieNotification object:remoteObject];

也许您的connectionDidDie:方法可以设置一个布尔变量,您可以在尝试发送消息之前对其进行检查。

您的 DO 可以发布通知说它已启动(尽管我认为也有系统消息,但我才刚刚开始了解 DO),您也可以类似地注册以收到它启动的通知。

我猜 Rob 的回答肯定是“包罗万象”,您不必担心通知中心没有及时接通服务器。

我一直在我的第一个 DO 应用程序中使用“did die”通知,希望对您有所帮助。

托德。

于 2012-05-12T09:03:59.047 回答