我正在尝试使用此代码建立套接字连接
//Server code
- (void)startServer{
sockPort = [[NSSocketPort alloc] initWithTCPPort:9786];
NSConnection *theConnection;
theConnection = [[NSConnection alloc] initWithReceivePort:sockPort sendPort:nil];
theConnection=[[NSConnection alloc] init];
[theConnection setRootObject:self];
[theConnection registerName:@"Server Connection"];
}
//Client Code
-(void)startClient{
NSConnection *conn=[NSConnection connectionWithReceivePort:nil sendPort:sockPort];
NSLog(@"Socket descriptor=%d",[sockPort socket]);
}
控制台
Socket descriptor=-1
为什么套接字描述符显示-1?
最佳答案
发布的代码没有特别的意义 - 但如果我们假设代码的客户端更传统一点并且看起来像:
- (void)startClient
{
NSSocketPort *sockPort = [[NSSocketPort alloc] initRemoteWithTCPPort: 1234
host: @"hostname"];
NSConnection *connection = [NSConnection connectionWithReceivePort: nil
sendPort: sockPort];
....
这里 sockPort 上的套接字应该是 -1,因为它并不代表该进程中的套接字,而是代表此类套接字应该连接到的目的地。
更有趣的是连接对象上的 receivePort 和 sendPort 属性。
关于objective-c - Objective-C 中的 NSSocketPort 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8587665/