简体   繁体   中英

connecting 2 devices over different WiFi network using GKSession

I am trying to connect 2 devices using GKSession. When the devices are on same WiFi network it is working but when i am trying to connect devices on different WiFi network it is not working. This is my code for GKSession

chatSession = [[GKSession alloc] initWithSessionID:AppName displayName:name sessionMode:GKSessionModePeer];
[chatSession setDataReceiveHandler:self withContext:nil];
chatSession.delegate = self;
chatSession.available = YES;



-(void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state{
NSLog(@"state=%d", state);
if(state == GKPeerStateDisconnected)
{
    // A peer disconnected
    chatSession.available = YES;
    NSLog(@"Disconnected");

    [data removeAllObjects];
    chatInput.hidden = YES;


}
else if(state == GKPeerStateConnected)
{
    // You can now send messages to the connected peer(s)


    NSData *imgData = UIImageJPEGRepresentation(myImage, 0.5);
    if(imgData==nil)
        NSLog(@"myImage is nil");

    NSError *err;
    //NSLog(@"pid=%@", pID);
    NSLog(@"before sending image");
    [chatSession sendData:imgData toPeers:[NSArray arrayWithObject:pID] withDataMode:GKSendDataReliable error:&err];
    NSLog(@"after send data");
    if(err)
        NSLog(@"error:%@", err.description);
}
else if (state == GKPeerStateAvailable)
{

    pID = peerID;
    [session connectToPeer:peerID withTimeout:60*120];
}

}

-(void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID{
// We can now decide to deny or accept
bool shouldAccept = YES;
if(shouldAccept)
{
    pID = peerID;
    [session acceptConnectionFromPeer:peerID error:nil];
}
else
{
    [session denyConnectionFromPeer:peerID];
}}

I am not sure if it is possible using GKSession.

According to Apple

A GKSession object provides the ability to discover and connect to nearby iOS devices using Bluetooth or Wi-fi.

Please help me ia m trying to create a chat app using GKSession.

iOS' GameKit most probably uses Bonjour for this, which works by doing broadcasts on a local network. It won't work between two separate Wi-Fi networks.

This means you'll need a central server (at least during connection set-up). Have a look at XMPP , if you haven't done so already.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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