How to choose which phone should be server and which one should be client?

236 views Asked by At

I'm developing an app right now, where (I'll keep it to the networking side of things) two devices would transfer data with each other (most likely some JSON data and maybe an image) after putting one phone on top of the other. I've got the device detection logic worked out, but now I'm stuck on the initiation: how would the two phones know which one will first be the client and which one will be the server, and then switch? I'm using Apple's Network Framework.

Maybe both devices choose a random number, 0 or 1, and then communicate the result with the other device, and the one which has 0 is the server and the one who has 1 is the client? And if they both got the same number start again? I don't have much experience in networking, so I'm really not sure.

PS: I tried using the MultipeerConnectivity framework, since it offers the peer-to-peer functionality I'm looking for, but it isn't being actively supported by Apple (meaning bad for future-proofing) and doesn't offer the customisability I'm looking for, which is why I decided to go a layer down with Network Framework, which is actively supported and easy to interface with.

1

There are 1 answers

2
Itay Brenner On

MultipeerConectivity and Network framework have different functions, with Network you can communicate creating a Client-Server architecture using TCP/UDP (and Websocket on top of TCP) and WiFi while MultipeerConectivity allows you to connect multiple devices through WiFi and Bluetooth. As you can see, they are not the same.

For Network Framework, there is a guide for Custom P2P connectivity made by Apple

I don't know what your app does, but generally one of the devices should be the Server/Listener, for example:

  • In a Chat app it would be the one to create the Room
  • In a game, it would be the one first to enter the game