SetupClient() function. This establishes a connection to the host and allows both players to begin the match.
How joining works
Create the client host
First, create a client-side ENet host:Passing
main.cpp
NULL as the first parameter creates a client host that can initiate connections but not accept them.Verify client creation
Check if the client host was created successfully:If creation fails, the game returns to the main menu.
main.cpp
Configure server address
Set up the address of the server to connect to:The
main.cpp
enet_address_set_host() function resolves the hostname or IP address (by default “127.0.0.1”) to an ENet address.Connect to the server
Initiate the connection to the server:This returns a peer object representing the connection to the server.
main.cpp
Complete SetupClient function
main.cpp
Network variables
The following global variables manage the client connection:main.cpp
When joining, the client uses
clientHost to manage its networking and stores the server connection in serverPeer.Connection to localhost vs LAN
By default, the game connects to127.0.0.1 (localhost), which only works if both players are on the same machine.
For LAN play, modify the SERVER_IP constant to the host’s local network IP address:
main.cpp
Troubleshooting
If connection fails:- Verify the server is running and in the
HOSTINGstate - Check that
SERVER_IPpoints to the correct host address - Ensure port 7777 is not blocked by firewall rules
- Confirm ENet has been initialized before calling
SetupClient()