我正在开发一款使用MPC的游戏。我得到了它的工作,但我发现连接(特别是超过2个对等体)经常失败。对等体开始连接(MCSessionState.Connecting),然后它们就没有(MCSessionState.NotConnected)。其他时候,它就像一个魅力。
这只是框架的问题,还是我可能做错了?
我跟着this tutorial。在我的实现中,其中一个播放器是浏览器,其余的是广告商。我提出的唯一解决方法是尝试再次连接,如果它获得.NotConnected标志,但有时它会尝试在成功之前重新连接3到4次(花费太长时间)。
以下是相关代码:
MPCManager(此类为MCSessionDelegate,MCNearbyServiceBrowserDelegate,MCNearbyServiceAdvertiserDelegate)
func advertiser(advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: NSData?, invitationHandler: (Bool, MCSession) -> Void) {
self.invitationHandler = invitationHandler
delegate?.invitationWasReceived(peerID.displayName)
}
// MARK: MCSessionDelegate method implementation
func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) {
switch state{
case MCSessionState.Connected:
print("Connected to session: \(session)")
connectedPeers.append(peerID)
delegate?.connectedWithPeer(peerID)
case MCSessionState.Connecting:
print("Connecting to session: \(session)")
default:
delegate?.disconnectedFromPeer(peerID)
print("Did not connect to session: \(session)")
}
}
委托类:
func invitationWasReceived(fromPeer: String) {
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.appDelegate.cManager!.invitationHandler(true, self.appDelegate.cManager!.session)
self.connectingLabel.text = "Connecting"
})
}
func connectedWithPeer(peerID: MCPeerID) {
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.connectingLabel.text = "Connected to \(peerID.displayName)"
if self.appDelegate.cManager!.connectedPeers.count == self.appDelegate.cManager!.foundPeers.count {
//game setup if all peers are connected
//stop browsing and advertising
}
})
}
func disconnectedFromPeer(peerID: MCPeerID) {
print("disconnected setup")
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.connectingLabel.text = "Couldn't connect to \(peerID.displayName)\n\nRetrying"
if self.isBrowser {
self.appDelegate.cManager!.browser.invitePeer(peerID, toSession: self.appDelegate.cManager!.session, withContext: nil, timeout: 20)
}
})
}
答案 0 :(得分:4)
- (void)session:(MCSession *)session didReceiveCertificate:(NSArray *)certificate fromPeer:(MCPeerID *)peerID certificateHandler:(void (^)(BOOL accept))certificateHandler
{
if (certificateHandler != nil)
{
certificateHandler(YES);
}
}