[OSX]プロセス間通信(Distributed Objects) | Cocoa練習帳

[OSX]プロセス間通信(Distributed Objects)

今度は、Distributed Objects。まずは、プロトコルを定義。


@protocol RemoteObjectProtocol
- (oneway void)receiveString:(NSString *)string;
@end

サーバ側を実装。クライアント側からのメソッド呼び出しに対応。


@interface AppDelegate () <RemoteObjectProtocol>
- (void)_registerForDistributedObjects;
@end
 
@implementation AppDelegate
 
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [self _registerForDistributedObjects];
}
 
- (void)_registerForDistributedObjects
{
    NSConnection    *conn = [NSConnection defaultConnection];
    [conn setRootObject:self];
    if ([conn registerName:@"DistributedServer"] == NO) {
        NSLog(@"%s error", __func__);
    }
}
 
- (oneway void)receiveString:(NSString *)string
{
    [self.label setStringValue:string];
}
 
@end

次は、クライアント側。


@interface AppDelegate ()
- (void)_postForDistributedObjects;
@end
 
@implementation AppDelegate
 
- (IBAction)postForDistributedObjects:(id)sender
{
    [self _postForDistributedObjects];
}
 
- (void)_postForDistributedObjects
{
    id  remoteObject;
    remoteObject = [NSConnection rootProxyForConnectionWithRegisteredName:@"DistributedServer"
                                                                     host:@""];
    [remoteObject setProtocolForProxy:@protocol(RemoteObjectProtocol)];
    [remoteObject receiveString:[NSString stringWithFormat:@"%@", [[NSDate date] description]]];
}
 
@end

名前DistributedServerでサーバを探して、プロトコルRemoteObjectProtocolのメソッドを呼ぶと、サーバ側のメソッドが実行される。


ソースコード
GitHubからどうぞ。

関連情報

【Cocoa練習帳】
Cocoa in a Nutshell: A Desktop Quick Reference/Oreilly & Associates Inc
¥5,008
Amazon.co.jp