为什么Multipeer连接如此之慢? [英] Why is Multipeer Connectivity so slow?
问题描述
所以,我在主线程中的所有multipeer连接相关的code。我有一个 MCSession,MCNearbyServiceAdvertiser和MCNearbyServiceBrowser
。这些都与创建的peerID,而我要确保的只有一个发送邀请。
会话连接变成。我的问题是这样的,两个客户端看看周围的 20-30秒进行连接。这是不可接受的。客户是良好的无线和蓝牙。我想浏览,邀请处理程序,并连接需要1秒内发生。没有人有任何的想法是什么速度变慢?
code是完全一样在这里提供,我还实施 certificateHandler(YES)
@interface SessionController()//类扩展
@属性(非原子,强)MCPeerID *的peerID;
@属性(非原子,强)MCSession *会议;
@属性(非原子,强)MCNearbyServiceAdvertiser * serviceAdvertiser;
@属性(非原子,强)MCNearbyServiceBrowser * serviceBrowser;//连接对等体存储在MCSession
//人工跟踪连接和断开同行
@属性(非原子,强)NSMutableOrderedSet * connectingPeersOrderedSet;
@属性(非原子,强)NSMutableOrderedSet * disconnectedPeersOrderedSet;
@结束@implementation SessionController静态的NSString * const的kMCSessionServiceType = @mcsessionp2p的#pragma马克 - 初始化程序 - (instancetype)INIT
{
自= [超级初始化] 如果(个体经营)
{
_peerID = [[MCPeerID页头] initWithDisplayName:[的UIDevice currentDevice]名称]]; _connectingPeersOrderedSet = [[NSMutableOrderedSet的alloc]初始化];
_disconnectedPeersOrderedSet = [[NSMutableOrderedSet的alloc]初始化]; NSNotificationCenter * defaultCenter = [NSNotificationCenter defaultCenter] //注册通知
[defaultCenter的addObserver:自我
选择:@selector(startServices)
名称:UIApplicationWillEnterForegroundNotification
对象:无]; [defaultCenter的addObserver:自我
选择:@selector(stopServices)
名称:使用UIApplicationDidEnterBackgroundNotification
对象:无]; [个体经营startServices] _displayName = self.session.myPeerID.displayName;
} 返回自我;
}的#pragma马克 - 内存管理 - (无效)的dealloc
{
//注销就释放通知。
[NSNotificationCenter defaultCenter] removeObserver:个体经营]; //无出代表
_session.delegate =零;
_serviceAdvertiser.delegate =零;
_serviceBrowser.delegate =零;
}的#pragma马克 - 重写属性访问器 - (NSArray的*)connectedPeers
{
返回self.session.connectedPeers;
} - (NSArray的*)connectingPeers
{
返回[self.connectingPeersOrderedSet阵列]
} - (NSArray的*)disconnectedPeers
{
返回[self.disconnectedPeersOrderedSet阵列]
}的#pragma马克 - 私有方法 - (无效)setupSession
{
//创建一个同龄人将被邀请会话/连接成。
_session = [[MCSession页头] initWithPeer:self.peerID];
self.session.delegate =自我; //创建服务广告
_serviceAdvertiser = [[MCNearbyServiceAdvertiser页头] initWithPeer:self.peerID
discoveryInfo:无
的serviceType:kMCSessionServiceType];
self.serviceAdvertiser.delegate =自我; //创建服务浏览器
_serviceBrowser = [[MCNearbyServiceBrowser页头] initWithPeer:self.peerID
的serviceType:kMCSessionServiceType];
self.serviceBrowser.delegate =自我;
} - (无效)teardownSession
{
[self.session断开]
[self.connectingPeersOrderedSet removeAllObjects]
[self.disconnectedPeersOrderedSet removeAllObjects]
} - (无效)startServices
{
[个体经营setupSession]
[self.serviceAdvertiser startAdvertisingPeer]
[self.serviceBrowser startBrowsingForPeers]
} - (无效)stopServices
{
[self.serviceBrowser stopBrowsingForPeers]
[self.serviceAdvertiser stopAdvertisingPeer]
[个体经营teardownSession]
} - (无效)updateDelegate
{
[self.delegate sessionDidChangeState]
} - (的NSString *)stringForPeerConnectionState:(MCSessionState)状态
{
开关(州){
案例MCSessionStateConnected:
返回@已连接; 案例MCSessionStateConnecting:
返回@正在连接; 案例MCSessionStateNotConnected:
返回@未连接;
}
}的#pragma马克 - MCSessionDelegate协议一致性 - (无效)会话:(MCSession *)会话同行:(MCPeerID *)的peerID didChangeState:(MCSessionState)状态
{
的NSLog(@同伴[%@]更改状态%@,peerID.displayName,[个体经营stringForPeerConnectionState:状态]); 开关(州)
{
案例MCSessionStateConnecting:
{
[self.connectingPeersOrderedSet ADDOBJECT:的peerID];
[self.disconnectedPeersOrderedSet的removeObject:的peerID];
打破;
} 案例MCSessionStateConnected:
{
[self.connectingPeersOrderedSet的removeObject:的peerID];
[self.disconnectedPeersOrderedSet的removeObject:的peerID];
打破;
} 案例MCSessionStateNotConnected:
{
[self.connectingPeersOrderedSet的removeObject:的peerID];
[self.disconnectedPeersOrderedSet ADDOBJECT:的peerID];
打破;
}
} [个体经营updateDelegate]
} - (无效)会话:(MCSession *)会议didReceiveData:(NSData的*)数据fromPeer:(MCPeerID *)的peerID
{
//德code输入数据到UTF8 EN codeD字符串
* NSString的receivedMessage = [[NSString的页头] initWithData:数据编码:NSUTF8StringEncoding]; 的NSLog(@didReceiveData%从%@@,receivedMessage,peerID.displayName);
} - (无效)会话:(MCSession *)会议didStartReceivingResourceWithName:(* NSString的)资源名称fromPeer:(MCPeerID *)的peerID withProgress:(NSProgress *)的进展
{
的NSLog(@didStartReceivingResourceWithName [%@]从%@同进[%@]资源名称,peerID.displayName,进度);
} - (无效)会话:(MCSession *)会议didFinishReceivingResourceWithName:(* NSString的)资源名称fromPeer:(MCPeerID *)的peerID atURL:(NSURL *)localURL withError:(NSError *)错误
{
的NSLog(@didFinishReceivingResourceWithName [%@]从%@,资源名称,peerID.displayName); //如果误差不为零出事了
如果(错误)
{
的NSLog(@错误[%@]从%@接收资源,[错误localizedDescription],peerID.displayName);
}
其他
{
//没有错误,所以这是一个完整的传输。所述资源位于一个临时位置,并应立即复制到permenant位置。
//写入文件目录
NSArray的*路径= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
* NSString的copyPath = [的NSString stringWithFormat:@%@ /%@,[路径firstObject],资源名称]
如果([的NSFileManager defaultManager] copyItemAtPath:[localURL路径] toPath:copyPath错误:无]!)
{
的NSLog(@错误复制资源文件的目录);
}
其他
{
//获取路径的URL,我们刚才复制的资源
NSURL * URL = [NSURL fileURLWithPath:copyPath];
的NSLog(@URL =%@,URL);
}
}
}在这code样品未使用//流API
- (无效)会话:(MCSession *)会议didReceiveStream:(NSInputStream *)流withName:(* NSString的)streamName中fromPeer:(MCPeerID *)的peerID
{
的NSLog(@didReceiveStream%从%@@,streamName中,peerID.displayName);
}的#pragma马克 - MCNearbyServiceBrowserDelegate协议一致性//找到附近的一个广告同行
- (无效)浏览器:(MCNearbyServiceBrowser *)浏览器foundPeer:(MCPeerID *)的peerID withDiscoveryInfo:(NSDictionary的*)信息
{
* NSString的= remotePeerName peerID.displayName; 的NSLog(@浏览器找到%@,remotePeerName); MCPeerID * myPeerID = self.session.myPeerID; BOOL shouldInvite =(myPeerID.displayName比较:remotePeerName] == NSOrderedDescending); 如果(shouldInvite)
{
的NSLog(@邀请%@,remotePeerName);
[浏览器invitePeer:的peerID toSession:self.session withContext:无超时:30.0];
}
其他
{
的NSLog(@不邀请%@,remotePeerName);
} [个体经营updateDelegate]
} - (无效)浏览器:(MCNearbyServiceBrowser *)浏览器lostPeer:(MCPeerID *)的peerID
{
的NSLog(@lostPeer%@,peerID.displayName); [self.connectingPeersOrderedSet的removeObject:的peerID];
[self.disconnectedPeersOrderedSet ADDOBJECT:的peerID]; [个体经营updateDelegate]
} - (无效)浏览器:(MCNearbyServiceBrowser *)浏览器didNotStartBrowsingForPeers:(NSError *)错误
{
的NSLog(@didNotStartBrowsingForPeers:%@,错误);
}的#pragma马克 - MCNearbyServiceAdvertiserDelegate协议一致性 - (无效)广告:(MCNearbyServiceAdvertiser *)广告didReceiveInvitationFromPeer:(MCPeerID *)的peerID withContext:(NSData的*)环境invitationHandler:(无效(^)(BOOL接受,MCSession *会话))invitationHandler
{
的NSLog(@didReceiveInvitationFromPeer%@,peerID.displayName); invitationHandler(YES,self.session); [self.connectingPeersOrderedSet ADDOBJECT:的peerID];
[self.disconnectedPeersOrderedSet的removeObject:的peerID]; [个体经营updateDelegate]
} - (无效)广告:(MCNearbyServiceAdvertiser *)广告didNotStartAdvertisingPeer:(NSError *)错误
{
的NSLog(@didNotStartAdvertisingForPeers:%@,错误);
}@结束
我已经注意到这个问题并我似乎无法找出什么在这里发生的事情,这在调试时,有通知之间存在着巨大的延迟出现对于被解雇状态改变,或许是与视图本身。
更新:嗯,我想我想通的问题了一点阅读后,响应pretty很多即时现在,在视图中通知我推的过程中回像这样的主线:
- (无效)peerDidChangeStateWithNotification:(NSNotification *)通知{ MCPeerID *的peerID = [[通知用户信息] objectForKey:@的peerID];
* NSString的= peerDisplayName peerID.displayName;
MCSessionState状态= [[[通知用户信息] objectForKey:@状态]的intValue]; 如果(状态!= MCSessionStateConnecting){ 如果(状态== MCSessionStateConnected){
//添加用户
[arrConnectedDevices ADDOBJECT:peerDisplayName];
}
否则,如果(状态== MCSessionStateNotConnected){ //我们有联系
如果([arrConnectedDevices计数]&0){
INT indexOfPeer = [arrConnectedDevices indexOfObject:peerDisplayName];
[arrConnectedDevices removeObjectAtIndex:indexOfPeer];
}
}
} //推到了迅速反应主队列
dispatch_async(dispatch_get_main_queue()^(无效){ [collView reloadData]; BOOL peersExist =([appDelegate.mcManager.session connectedPeers]计数] == 0);
的NSLog(@PEER计数是%录,(无符号长)[appDelegate.mcManager.session connectedPeers]计数]);
[disconnectButton的setEnabled!peersExist]; 如果([disconnectButton isEnabled]){
[disconnectButton setBackgroundColor:[的UIColor colorWithRed:(51 / 255.0)绿:(202 / 255.0)蓝:(168 / 255.0)阿尔法:1.0];
}
其他{
[disconnectButton setBackgroundColor:[的UIColor colorWithRed:(107 / 255.0)绿:(107 / 255.0)蓝:(107 / 255.0)阿尔法:1.0];
} });}
希望这有助于人谁碰到了的问题。
So, I have all multipeer connectivity related code in the main thread. I have a MCSession, MCNearbyServiceAdvertiser, and a MCNearbyServiceBrowser
. These are all created with peerID, and I make sure only one sends an invitation.
The session becomes connected. My problems is that, two clients take around 20-30 seconds to connect. This is unacceptable. The clients are on good Wifi, and bluetooth. I want the browsing, invitation handler, and connection to take place within 1 second. Does anyone have any idea what is slowing things down?
Code is exactly as provided here and I also implemented certificateHandler(YES)
@interface SessionController () // Class extension
@property (nonatomic, strong) MCPeerID *peerID;
@property (nonatomic, strong) MCSession *session;
@property (nonatomic, strong) MCNearbyServiceAdvertiser *serviceAdvertiser;
@property (nonatomic, strong) MCNearbyServiceBrowser *serviceBrowser;
// Connected peers are stored in the MCSession
// Manually track connecting and disconnected peers
@property (nonatomic, strong) NSMutableOrderedSet *connectingPeersOrderedSet;
@property (nonatomic, strong) NSMutableOrderedSet *disconnectedPeersOrderedSet;
@end
@implementation SessionController
static NSString * const kMCSessionServiceType = @"mcsessionp2p";
#pragma mark - Initializer
- (instancetype)init
{
self = [super init];
if (self)
{
_peerID = [[MCPeerID alloc] initWithDisplayName:[[UIDevice currentDevice] name]];
_connectingPeersOrderedSet = [[NSMutableOrderedSet alloc] init];
_disconnectedPeersOrderedSet = [[NSMutableOrderedSet alloc] init];
NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
// Register for notifications
[defaultCenter addObserver:self
selector:@selector(startServices)
name:UIApplicationWillEnterForegroundNotification
object:nil];
[defaultCenter addObserver:self
selector:@selector(stopServices)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[self startServices];
_displayName = self.session.myPeerID.displayName;
}
return self;
}
#pragma mark - Memory management
- (void)dealloc
{
// Unregister for notifications on deallocation.
[[NSNotificationCenter defaultCenter] removeObserver:self];
// Nil out delegates
_session.delegate = nil;
_serviceAdvertiser.delegate = nil;
_serviceBrowser.delegate = nil;
}
#pragma mark - Override property accessors
- (NSArray *)connectedPeers
{
return self.session.connectedPeers;
}
- (NSArray *)connectingPeers
{
return [self.connectingPeersOrderedSet array];
}
- (NSArray *)disconnectedPeers
{
return [self.disconnectedPeersOrderedSet array];
}
#pragma mark - Private methods
- (void)setupSession
{
// Create the session that peers will be invited/join into.
_session = [[MCSession alloc] initWithPeer:self.peerID];
self.session.delegate = self;
// Create the service advertiser
_serviceAdvertiser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:self.peerID
discoveryInfo:nil
serviceType:kMCSessionServiceType];
self.serviceAdvertiser.delegate = self;
// Create the service browser
_serviceBrowser = [[MCNearbyServiceBrowser alloc] initWithPeer:self.peerID
serviceType:kMCSessionServiceType];
self.serviceBrowser.delegate = self;
}
- (void)teardownSession
{
[self.session disconnect];
[self.connectingPeersOrderedSet removeAllObjects];
[self.disconnectedPeersOrderedSet removeAllObjects];
}
- (void)startServices
{
[self setupSession];
[self.serviceAdvertiser startAdvertisingPeer];
[self.serviceBrowser startBrowsingForPeers];
}
- (void)stopServices
{
[self.serviceBrowser stopBrowsingForPeers];
[self.serviceAdvertiser stopAdvertisingPeer];
[self teardownSession];
}
- (void)updateDelegate
{
[self.delegate sessionDidChangeState];
}
- (NSString *)stringForPeerConnectionState:(MCSessionState)state
{
switch (state) {
case MCSessionStateConnected:
return @"Connected";
case MCSessionStateConnecting:
return @"Connecting";
case MCSessionStateNotConnected:
return @"Not Connected";
}
}
#pragma mark - MCSessionDelegate protocol conformance
- (void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state
{
NSLog(@"Peer [%@] changed state to %@", peerID.displayName, [self stringForPeerConnectionState:state]);
switch (state)
{
case MCSessionStateConnecting:
{
[self.connectingPeersOrderedSet addObject:peerID];
[self.disconnectedPeersOrderedSet removeObject:peerID];
break;
}
case MCSessionStateConnected:
{
[self.connectingPeersOrderedSet removeObject:peerID];
[self.disconnectedPeersOrderedSet removeObject:peerID];
break;
}
case MCSessionStateNotConnected:
{
[self.connectingPeersOrderedSet removeObject:peerID];
[self.disconnectedPeersOrderedSet addObject:peerID];
break;
}
}
[self updateDelegate];
}
- (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID
{
// Decode the incoming data to a UTF8 encoded string
NSString *receivedMessage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"didReceiveData %@ from %@", receivedMessage, peerID.displayName);
}
- (void)session:(MCSession *)session didStartReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID withProgress:(NSProgress *)progress
{
NSLog(@"didStartReceivingResourceWithName [%@] from %@ with progress [%@]", resourceName, peerID.displayName, progress);
}
- (void)session:(MCSession *)session didFinishReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID atURL:(NSURL *)localURL withError:(NSError *)error
{
NSLog(@"didFinishReceivingResourceWithName [%@] from %@", resourceName, peerID.displayName);
// If error is not nil something went wrong
if (error)
{
NSLog(@"Error [%@] receiving resource from %@ ", [error localizedDescription], peerID.displayName);
}
else
{
// No error so this is a completed transfer. The resources is located in a temporary location and should be copied to a permenant location immediately.
// Write to documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *copyPath = [NSString stringWithFormat:@"%@/%@", [paths firstObject], resourceName];
if (![[NSFileManager defaultManager] copyItemAtPath:[localURL path] toPath:copyPath error:nil])
{
NSLog(@"Error copying resource to documents directory");
}
else
{
// Get a URL for the path we just copied the resource to
NSURL *url = [NSURL fileURLWithPath:copyPath];
NSLog(@"url = %@", url);
}
}
}
// Streaming API not utilized in this sample code
- (void)session:(MCSession *)session didReceiveStream:(NSInputStream *)stream withName:(NSString *)streamName fromPeer:(MCPeerID *)peerID
{
NSLog(@"didReceiveStream %@ from %@", streamName, peerID.displayName);
}
#pragma mark - MCNearbyServiceBrowserDelegate protocol conformance
// Found a nearby advertising peer
- (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info
{
NSString *remotePeerName = peerID.displayName;
NSLog(@"Browser found %@", remotePeerName);
MCPeerID *myPeerID = self.session.myPeerID;
BOOL shouldInvite = ([myPeerID.displayName compare:remotePeerName] == NSOrderedDescending);
if (shouldInvite)
{
NSLog(@"Inviting %@", remotePeerName);
[browser invitePeer:peerID toSession:self.session withContext:nil timeout:30.0];
}
else
{
NSLog(@"Not inviting %@", remotePeerName);
}
[self updateDelegate];
}
- (void)browser:(MCNearbyServiceBrowser *)browser lostPeer:(MCPeerID *)peerID
{
NSLog(@"lostPeer %@", peerID.displayName);
[self.connectingPeersOrderedSet removeObject:peerID];
[self.disconnectedPeersOrderedSet addObject:peerID];
[self updateDelegate];
}
- (void)browser:(MCNearbyServiceBrowser *)browser didNotStartBrowsingForPeers:(NSError *)error
{
NSLog(@"didNotStartBrowsingForPeers: %@", error);
}
#pragma mark - MCNearbyServiceAdvertiserDelegate protocol conformance
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void(^)(BOOL accept, MCSession *session))invitationHandler
{
NSLog(@"didReceiveInvitationFromPeer %@", peerID.displayName);
invitationHandler(YES, self.session);
[self.connectingPeersOrderedSet addObject:peerID];
[self.disconnectedPeersOrderedSet removeObject:peerID];
[self updateDelegate];
}
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didNotStartAdvertisingPeer:(NSError *)error
{
NSLog(@"didNotStartAdvertisingForPeers: %@", error);
}
@end
I've noticed this issue to and i can't seem to figure out whats happening here, it appears when debugging that there is a huge delay between the notification for state changing being fired, perhaps something to do with the view itself.
Update: Well i think i figured the issues out after a bit of reading, the response is pretty much instant now, in the notification in the view i have pushed the process back to the main thread like so:
-(void)peerDidChangeStateWithNotification:(NSNotification *)notification{
MCPeerID *peerID = [[notification userInfo] objectForKey:@"peerID"];
NSString *peerDisplayName = peerID.displayName;
MCSessionState state = [[[notification userInfo] objectForKey:@"state"] intValue];
if (state != MCSessionStateConnecting) {
if (state == MCSessionStateConnected) {
// add the user
[arrConnectedDevices addObject:peerDisplayName];
}
else if (state == MCSessionStateNotConnected){
// do we have connections
if ([arrConnectedDevices count] > 0) {
int indexOfPeer = [arrConnectedDevices indexOfObject:peerDisplayName];
[arrConnectedDevices removeObjectAtIndex:indexOfPeer];
}
}
}
// push to main queue for speedy response
dispatch_async(dispatch_get_main_queue(), ^(void) {
[collView reloadData];
BOOL peersExist = ([[appDelegate.mcManager.session connectedPeers] count] == 0);
NSLog(@"PEER COUNT IS %lu",(unsigned long)[[appDelegate.mcManager.session connectedPeers] count]);
[disconnectButton setEnabled:!peersExist];
if ([disconnectButton isEnabled]) {
[disconnectButton setBackgroundColor:[UIColor colorWithRed:(51/255.0) green:(202/255.0) blue:(168/255.0) alpha:1.0]];
}
else{
[disconnectButton setBackgroundColor:[UIColor colorWithRed:(107/255.0) green:(107/255.0) blue:(107/255.0) alpha:1.0]];
}
});
}
Hope this helps anyone who ran into the issues.
这篇关于为什么Multipeer连接如此之慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!