我是Cocoa编程的新手......我正在学习使用Distributed Objects的IPC。 我做了一个简单的例子,我从服务器出售对象并在客户端中调用它们。我成功地将消息从客户端对象传递到服务器但是我想将消息从服务器传递给客户端[双向] ...如何我这样做了吗?
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
MYMessageServer *server = [[MYMessageServer alloc] init];
NSConnection *defaultConnection=[NSConnection defaultConnection];
[defaultConnection setRootObject:server];
if ([defaultConnection registerName:@"server"] == NO)
{
NSLog(@"Error registering server");
}
else
NSLog(@"Connected");
[[NSRunLoop currentRunLoop] configureAsServer];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
//Getting an Vended Object
server = [NSConnection rootProxyForConnectionWithRegisteredName:@"server" host:nil];
if(nil == server)
{
NSLog(@"Error: Failed to connect to server.");
}
else
{
//setProtocolForProxy is a method of NSDistantObject
[server setProtocolForProxy:@protocol(MYMessageServerProtocol)];
[server addMessageClient:self];
[server broadcastMessageString:[NSString stringWithFormat:@"Connected: %@ %d\n",
[[NSProcessInfo processInfo] processName],
[[NSProcessInfo processInfo] processIdentifier]]];
}
}
- (void)appendMessageString:(NSString *)aString
{
NSRange appendRange = NSMakeRange([[_messageView string] length], 0);
// Append text and scroll if neccessary
[_messageView replaceCharactersInRange:appendRange withString:aString];
[_messageView scrollRangeToVisible:appendRange];
}
- (void)addMessageClient:(id)aClient
{
if(nil == _myListOfClients)
{
_myListOfClients = [[NSMutableArray alloc] init];
}
[_myListOfClients addObject:aClient];
NSLog(@"Added client");
}
- (BOOL)removeMessageClient:(id)aClient
{
[_myListOfClients removeObject:aClient];
NSLog(@"Removed client");
return YES;
}
- (void)broadcastMessageString:(NSString *)aString
{
NSLog(@"Msg is %@",aString);
self.logStatement = aString;
[_myListOfClients makeObjectsPerformSelector:@selector(appendMessageString:)
withObject:aString];
}
@protocol MYMessageServerProtocol
- (void)addMessageClient:(id)aClient;
- (BOOL)removeMessageClient:(id)aClient;
- (void)broadcastMessageString:(NSString *)aString;
答案 0 :(得分:0)
您尚未显示MYMessageServer
或MYMessageServerProtocol
的代码,特别是-addMessageClient:
方法。但是,一旦您向服务器传递了对客户端中对象的引用,服务器就可以像正常一样向该对象发送消息,并且该消息将通过D.O.发送。给客户。
因此,客户端通过self
将-addMessageClient:
(其应用程序委托)发送到服务器。服务器可以简单地调用它在-addMessageClient:
实现中接收的对象上的方法,并调用客户端应用程序委托对象上的方法。服务器可以在某处保留该引用,例如实例变量中的客户端数组,并且如果需要,也可以在以后继续向客户端发送消息。服务器将在连接关闭时清除该引用,它可以从NSConnection
发布的通知中检测到。