2010-04-15 89 views
2

我想使用NSConnection/NSDistributedObject進行進程間通信。我希望客戶端能夠處理服務器偶爾可以訪問的情況。檢測/修復NSConnection失敗

如何確定向NSConnection發送消息是失敗還是失敗?目前,如果我的服務器(已經售出遠程對象的進程)死亡,則客戶端將崩潰如果它向遠程對象發送選擇器。

理想情況下,我想爲遠程對象提供一個包裝,它可以懶惰地實例化(或重新實例化)連接,並在連接無法實例化或連接失敗的情況下返回默認值。我真的不知道使用目標c來做到這一點的正確方法。

這裏是代表這個邏輯的僞代碼:

if myConnection is null: 
    instantiate myConnection 
    if MyConnection is null: 
     return defaultValue 

    try 
     return [myConnection someMethod] 
    catch 
     myConnection = null 
     return defaultValue 

回答

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

如果你的服務器是正常在quiting然後,我的理解,它會發佈一個NSConnectionDidDieNotification,因爲它是連接關閉,所以你可以註冊你的客戶是這樣的:

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

也許你的connectionDidDie:方法可以設置一個布爾變量,你可以在嘗試發送消息之前檢查。

你的DO可以發佈通知說它已經啓動了(雖然我認爲也有系統消息,但是我剛剛開始瞭解DO的相關知識),並且你可以通過類似的方式註冊以獲得啓動通知。

我想羅布的回答是明確的「包羅萬象」,你就不必擔心有沒有通過及時服務器得到了通知中心。

我一直在使用它在我的第一DO應用程序中的「沒有死」的通知,我希望它可以幫助你。

託德。