【问题标题】:Detecting/Repairing NSConnection failure检测/修复 NSConnection 失败
【发布时间】:2011-02-08 14:16:49
【问题描述】:

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

【问题讨论】:

    标签: objective-c cocoa nsconnection


    【解决方案1】:

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

    //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
    }
    

    【讨论】:

      【解决方案2】:

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

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

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

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

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

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

      托德。

      【讨论】:

        猜你喜欢
        • 2016-09-09
        • 1970-01-01
        • 2021-12-16
        • 2010-10-16
        • 1970-01-01
        • 2020-01-06
        • 2015-04-18
        • 1970-01-01
        • 2017-07-13
        相关资源
        最近更新 更多