我对Cocoa编程很陌生.我正在学习带有分布式对象的IPC。我做了一个简单的例子,我从服务器上销售对象并在客户端调用它们,我成功地将消息从客户端对象传递到服务器,但是我想将消息从服务器传递到clientBidirectional...How,我做到了吗?
- (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;发布于 2015-08-12 15:07:17
您还没有展示MYMessageServer或MYMessageServerProtocol的代码,特别是-addMessageClient:方法。但是,一旦您向服务器传递了对客户端中某个对象的引用,服务器就可以像往常一样向该对象发送消息,并且该消息将通过D.O.发送给客户端。
因此,客户端通过self向服务器发送-addMessageClient: (其应用程序委托)。服务器可以简单地调用它在-addMessageClient:实现中接收到的对象上的方法,这将调用客户端的应用程序委托对象上的方法。服务器可以将该引用保存在某个地方,例如实例变量中的客户端数组,并在以后的时间继续向客户机发送消息(如果需要的话)。服务器希望在连接关闭时清除该引用,它可以从NSConnection发布的通知中检测到该引用。
https://stackoverflow.com/questions/31967098
复制相似问题