我已经使用GCDAsyncSocket来连接两个设备。一个设备广播它自己并接受连接,另一个设备监听并请求连接。
如果我尝试将另一个设备连接到正在广播的主机上,它会连接,然后在第一个设备仍然连接时获得连接终止!
我该如何重构我的代码以接受多个连接?我错过了什么?请帮帮我,我一直在努力解决这个问题!这是我的代码:
- (void)startBroadcast {
// Initialize GCDAsyncSocket
self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
// Start Listening for Incoming Connections
NSError *error = nil;
if ([self.socket acceptOnPort:0 error:&error]) {
// Initialize Service
self.service = [[NSNetService alloc] initWithDomain:@"local." type:@"_iQuest._tcp." name:@"" port:[self.socket localPort]];
// Configure Service
[self.service setDelegate:self];
// Publish Service
[self.service publish];
} else {
NSLog(@"Unable to create socket. Error %@ with user info %@.", error, [error userInfo]);
}
}
- (void)socket:(GCDAsyncSocket *)socket didAcceptNewSocket:(GCDAsyncSocket *)newSocket {
NSLog(@"Accepted New Socket from %@:%hu", [newSocket connectedHost], [newSocket connectedPort]);
NSString *alertmsg = [NSString stringWithFormat:@"Client is now connected to %@.", self.service.name];
UIAlertView *Connection = [[UIAlertView alloc] initWithTitle:@"Connection Success!" message:alertmsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[Connection show];
[self setSocket:newSocket];
[connectedSockets addObject:newSocket];
// Read Data from Socket
[newSocket readDataToLength:sizeof(uint64_t) withTimeout:-1.0 tag:0];
}
- (void)socket:(GCDAsyncSocket *)socket didReadData:(NSData *)data withTag:(long)tag {
if (tag == 0) {
uint64_t bodyLength = [self parseHeader:data];
[socket readDataToLength:bodyLength withTimeout:-1.0 tag:1];
} else if (tag == 1) {
[self parseBody:data];
[socket readDataToLength:sizeof(uint64_t) withTimeout:-1.0 tag:0];
}
}
[self setSocket:newSocket]
的调用看起来有些可疑。这个方法是做什么的?它能正确处理多个连接的套接字吗? - Paulw11