I am writing a simple multiplayer 2d game, 4 player Pong to be exact.
When the game starts There is a start Menu where you can choose to host or join a game.
one of the 4 players has to host, the other 3 will join. I can yell across the room to my other 3 buddies and tell them my ip and port number, but I am wondering if there is a way to search for the host instead. To me it sounds impossible, there are millions of computers on the internet, how can I possibly find the one computer who is waiting for my call. I know StarCraft Used to do it in the mid 90’s.
I have one theory on how I can achieve this. That is using a database like sql to keep track of who is currently Hosting. This would be the only use of the database since I am not keeping user stats or anything.
Is there a better way to do this?
Assuming you’re on a LAN, you can use UDP to discover clients.
If a client is acting as a host, it listens for UDP datagrams. If it receives one containing a discovery request, it responds with its IP, port and any other information that the client needs. (You can include number of connected players, etc.)
If a client is acting as, well, a client, it sends discovery datagrams while on the “join a game” screen. As hosts respond, they are added to the selection list.
When the user selects a server, connect over IP as you’re already doing using the IP and port that you received in the discovery response.
The Lidgren network library provides some nice Discovery functionality that may be of use.
If you’re not on a LAN, you’ll need some sort of central directory that’s globally accessible- probably on a website. When someone starts a new game, their client would register their IP, etc. with the directory. Clients would then poll that site to get a list of servers, which would then be used to populate the “Join a game” screen.
It’s worth noting that the server/directory approach works just as well in a LAN environment as it does over the Internet. UDP is more flexible in that it doesn’t require that a client have any knowledge of a directory provider, since it basically “yells across the room” for you.