0

我正在尝试使用 a 在同一台计算机上的两个应用程序之间创建连接NSSocketPort,但它似乎只以一种方式工作。我有一个服务器,它创建 aNSMutableDictionary并将其设置为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"很好,但是当我让服务器读取[self.conn rootProxy]客户端设置后"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给服务器吗?我怎样才能做到这一点?

4

1 回答 1

0

我设法通过实现一个实现协议的类来解决这个问题,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];

插座型号:

@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];

我什至可以在 my 上创建一个委托SocketModel并将其分配给我的客户端,这使得服务器向客户端提供进度信息。

于 2014-09-22T07:27:50.233 回答