NSSocketPort端口只能以一种方式工作

时间:2014-04-16 08:14:37

标签: objective-c macos nssocketport

我正在尝试使用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"就好了,但是当我让服务器在客户端设置[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返回给服务器吗?我怎么能这样做?

1 个答案:

答案 0 :(得分: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];

<强> 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上创建委托并将其分配给我的客户端,这使服务器向客户端提供进度信息。