我试图用NSSocketPort在同一台计算机上的两个应用程序之间创建一个连接,但它似乎只是一种方式。我有一个服务器,它创建一个NSMutableDictionary并将其设置为rootObject。客户端读取rootProxy,并在服务器创建它时获取字典。但是,我希望客户机向字典中添加一个额外的键/值集,并再次将字典设置为rootObject。但是,服务器似乎没有收到客户端设置后的最后一个值/键集。
服务器:
self.portRecv = [[NSSocketPort alloc] initWithTCPPort:30028];
self.conn = [NSConnection connectionWithReceivePort:self.portRecv sendPort:nil];
self.data = [NSMutableDictionary dictionary];
[self.data setObject:@"Value" forKey:@"serverSet"];
self.conn.rootObject = self.data;
self.conn.delegate = self;以下是服务器读取值的方式:
self.data = (NSMutableDictionary*)[self.conn rootProxy];客户端:
self.portSend = [[NSSocketPort alloc] initRemoteWithTCPPort:30028 host:@"127.0.0.1"];
self.conn = [NSConnection connectionWithReceivePort:nil sendPort:self.portSend];
self.conn.delegate = self;
self.data = (NSMutableDictionary*)[self.conn rootProxy];
[self.data setObject:@"Value" forKey:@"clientSet"];
self.conn.rootObject = self.data;客户端的self.data可以很好地接收"serverSet : Value",但是当客户机设置了"clientSet : Value"之后,当我让服务器读取"clientSet : Value"时,服务器会得到一个带有serverSet值的字典,而不是clientSet。
我现答覆各位代表的致辞如下:
- (BOOL)makeNewConnection:(NSConnection *)conn sender:(NSConnection *)ancestor
{
return YES;
}
- (BOOL)connection:(NSConnection *)ancestor shouldMakeNewConnection:(NSConnection *)conn
{
return YES;
}
- (BOOL)connection:(NSConnection *)conn handleRequest:(NSDistantObjectRequest *)doReq
{
NSInvocation *invocation = [doReq invocation];
[invocation invoke];
if ([invocation selector] == @selector(entitiesByName))
{
id retVal;
[invocation getReturnValue:&retVal];
NSDictionary *rebuilt = [NSDictionary dictionaryWithDictionary:retVal];
[invocation setReturnValue:&rebuilt];
}
[doReq replyWithException:nil];
return YES;
}难道我不能添加一个值并将rootObject返回到服务器吗?我怎么能这么做?
发布于 2014-09-22 07:27:50
我设法通过实现一个实现NSCoding协议的类来解决这个问题,然后使用它作为rootObject。通过这样做,我能够从客户机调用服务器对象上的不同方法。
结果是这样的:
服务器:
int port = 30012;
self.socketModel = [[SocketModel alloc] init];
self.socketModel.statusBarUiDelegate = self;
NSSocketPort* recvPort = [[NSSocketPort alloc] initWithTCPPort:port];
self.conn = [NSConnection connectionWithReceivePort:recvPort sendPort:nil];
[self.conn setRootObject:self.socketModel];SocketModel:
@interface SocketModel : NSObject<NSCoding>
-(NSString*)performTask:(NSString*)data;
-(void)taskCompleted;
@end客户端:
NSString* data = @"pewpew";
NSSocketPort* recv = [[NSSocketPort alloc] initRemoteWithTCPPort:30012 host:@"127.0.0.1"];
self.conn = [NSConnection connectionWithReceivePort:nil sendPort:recv];
[self.conn setRequestTimeout:5];
NSString* result = nil;
SocketModel* obj = nil;
obj = (SocketModel*)[self.conn rootProxy];
result = [builderObj performTask:data];
[obj taskCompleted];我甚至能够在我的SocketModel上创建一个委托并将它分配给我的客户机,这使得服务器向客户机提供进度信息。
https://stackoverflow.com/questions/23103668
复制相似问题