简体   繁体   English

创建P2P连接iOS

[英]Creating p2p connection iOS

Okay. 好的。 So I have been trying to connect devices p2p with streams for a week. 所以我一直在尝试将设备p2p与流连接一周。 Still no result and i am getting crazy and desperate. 仍然没有结果,我变得疯狂和绝望。 Please Don't send me to Ray Wenderlich tutorial and GCD wiki or to CFStream Guide as i have surfed it to the holes. 请不要将我发送到Ray Wenderlich教程和GCD Wiki或CFStream指南,因为我已经将其冲浪了。

So 1) Variant Here i 所以1)变体我

  1. Get Ip Of My device 获取我的设备的IP
  2. Manually input ip in text field of other device 在其他设备的文本字段中手动输入IP
  3. Init network communication on one device. 在一个设备上初始化网络通信。
  4. Error - connecting to host. 错误-连接到主机。

      + (NSString *)getIPAddress { NSString *address = @"error"; struct ifaddrs *interfaces = NULL; struct ifaddrs *temp_addr = NULL; int success = 0; // retrieve the current interfaces - returns 0 on success success = getifaddrs(&interfaces); if (success == 0) { // Loop through linked list of interfaces temp_addr = interfaces; while(temp_addr != NULL) { if(temp_addr->ifa_addr->sa_family == AF_INET) { // Check if interface is en0 which is the wifi connection on the iPhone if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { // Get NSString from C String address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; } } temp_addr = temp_addr->ifa_next; } } // Free memory freeifaddrs(interfaces); return address; } 
    • (void) initNetworkCommunication:(NSString*)ipToConnect { NSString *urlStr = ipToConnect; (void)initNetworkCommunication:(NSString *)ipToConnect {NSString * urlStr = ipToConnect; if (![urlStr isEqualToString:@""]) { NSURL *website = [NSURL URLWithString:urlStr]; 如果(![urlStr isEqualToString:@“”]){NSURL * website = [NSURL URLWithString:urlStr]; if (!website) { NSLog(@"%@ is not a valid URL"); 如果(!website){NSLog(@“%@不是有效的URL”); return; 返回; } CFReadStreamRef readStream; } CFReadStreamRef readStream; CFWriteStreamRef writeStream; CFWriteStreamRef writeStream; CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)[website host], 80, &readStream, &writeStream); CFStreamCreatePairWithSocketToHost(NULL,(__bridge CFStringRef)[网站主机],80,&readStream,&writeStream);

    NSInputStream *inputStream = (__bridge_transfer NSInputStream *)readStream; NSInputStream * inputStream =(__bridge_transfer NSInputStream *)readStream; NSOutputStream *outputStream = (__bridge_transfer NSOutputStream *)writeStream; NSOutputStream * outputStream =(__bridge_transfer NSOutputStream *)writeStream; [inputStream setDelegate:self]; [inputStream setDelegate:self]; [outputStream setDelegate:self]; [outputStream setDelegate:self]; [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [inputStream open]; [inputStream打开]; [outputStream open]; [outputStream打开];

    } }

    • (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent { (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

    NSLog(@"stream event %lu", streamEvent); NSLog(@“ stream event%lu”,streamEvent);

    switch (streamEvent) { 开关(streamEvent){

     case NSStreamEventOpenCompleted: NSLog(@"Stream opened"); break; case NSStreamEventHasBytesAvailable: if (theStream == inputStream) { uint8_t buffer[1024]; int len; while ([inputStream hasBytesAvailable]) { len = [inputStream read:buffer maxLength:sizeof(buffer)]; if (len > 0) { NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding]; if (nil != output) { NSLog(@"server said: %@", output); //[self messageReceived:output]; } } } } break; case NSStreamEventErrorOccurred: NSLog(@"Can not connect to the host!"); break; case NSStreamEventEndEncountered: [theStream close]; [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; // [theStream release]; theStream = nil; break; default: NSLog(@"Unknown event"); 

    } }

    } }

Variant 2 with GCD. GCD的变体2。 1. Same 2. Set both devices to listen to input 1.相同2.设置两个设备以监听输入

+(void)listenSocket:(GCDAsyncSocket*)listenSocket
{

listenSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

NSError *error = nil;
if (![listenSocket acceptOnPort:80 error:&error])
{
    NSLog(@"I goofed: %@", error);
}

}

3) Tried to connect with manually inputting IP 3)尝试连接手动输入IP

 +(void)connectToDeviceWithIp:(NSString*)deviceIp andSend:(HSUserCard*)tempCard andSocket:(GCDAsyncSocket*)tempSocket
{

tempSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *err = nil;
if (![tempSocket connectToHost:deviceIp onPort:80 error:&err])
    NSLog(@"I goofed: %@", err);



[tempSocket writeData:[NSKeyedArchiver archivedDataWithRootObject:tempCard] withTimeout:-1 tag:1];
}

4) Result nothing - i did put several breaks on every delegate function =NOTHING. 4)什么都没有结果-我确实在每个委托函数= NOTHING上都做了几次休息。

Omg - i solved this task on Android in 20 minutes! 天哪-我在20分钟内在Android上解决了这个任务! But here it just drives crazy. 但是在这里,它只会发疯。 Tried in several networks. 在多个网络中尝试过。 Thrue 3g, home wifi. 穿过3克,家用wifi。 Please someone help! 请有人帮忙!

The problem I can see from all of your various attempts is that you are storing the socket in a local variable - this means that once the method exits it will be released and no communications will be possible on that socket. 从所有尝试中可以看到的问题是,您将套接字存储在本地变量中-这意味着一旦方法退出,它将被释放,并且该套接字上将无法进行任何通信。

You need to store your socket references in strong properties. 您需要将套接字引用存储在strong属性中。

I have created an example application using CocoaAsyncSocket that demonstrates listening for connections and making a connection along with tracking the connection state through properties holding the sockets. 我使用CocoaAsyncSocket创建了一个示例应用程序,该应用程序演示了侦听连接并进行连接以及通过持有套接字的属性跟踪连接状态。

It is available here https://github.com/paulw11/SocketDemo 它可以在这里https://github.com/paulw11/SocketDemo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM