Multipeer Connectivity 每个会话仅支持 8 个对等点,但它支持多个会话。在您的情况下,如果有一个带有许多客户端的“服务器”设备,并且客户端不需要互相看到,那么“服务器”可以根据需要创建新会话。
因此,当“服务器”对等方充当广告商并接受邀请时,有一种方法可以返回现有会话或创建新会话:
- (MCSession *)availableSession {
//Try and use an existing session (_sessions is a mutable array)
for (MCSession *session in _sessions)
if ([session.connectedPeers count]<kMCSessionMaximumNumberOfPeers)
return session;
//Or create a new session
MCSession *newSession = [self newSession];
[_sessions addObject:newSession];
return newSession;
}
- (MCSession *)newSession {
MCSession *session = [[MCSession alloc] initWithPeer:_myPeerID securityIdentity:nil encryptionPreference:MCEncryptionNone];
session.delegate = self;
return session;
}
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void (^)(BOOL, MCSession *))invitationHandler {
MCSession *session = [self availableSession];
invitationHandler(YES,session);
}
然后我有这种发送方法:
- (void)sendData:(NSData *)data toPeers:(NSArray *)peerIDs reliable:(BOOL)reliable error:(NSError *__autoreleasing *)error {
if ([peerIDs count]==0)
return;
NSPredicate *peerNamePred = [NSPredicate predicateWithFormat:@"displayName in %@", [peerIDs valueForKey:@"displayName"]];
MCSessionSendDataMode mode = (reliable) ? MCSessionSendDataReliable : MCSessionSendDataUnreliable;
//Need to match up peers to their session
for (MCSession *session in _sessions){
NSError __autoreleasing *currentError = nil;
NSArray *filteredPeerIDs = [session.connectedPeers filteredArrayUsingPredicate:peerNamePred];
[session sendData:data toPeers:filteredPeerIDs withMode:mode error:¤tError];
if (currentError && !error)
*error = currentError;
}
}
There are certainly performance optimizations that can be made to this approach, but for the frequency with which I am sending data to peers this has worked well enough.