Skip to main content
To join a multiplayer game, a player must connect to an existing server using the SetupClient() function. This establishes a connection to the host and allows both players to begin the match.

How joining works

1

Create the client host

First, create a client-side ENet host:
main.cpp
Passing NULL as the first parameter creates a client host that can initiate connections but not accept them.
2

Verify client creation

Check if the client host was created successfully:
main.cpp
If creation fails, the game returns to the main menu.
3

Configure server address

Set up the address of the server to connect to:
main.cpp
The enet_address_set_host() function resolves the hostname or IP address (by default “127.0.0.1”) to an ENet address.
4

Connect to the server

Initiate the connection to the server:
main.cpp
This returns a peer object representing the connection to the server.
5

Wait for connection confirmation

The game enters the JOINING state and waits for the connection to be established:
main.cpp
Once the connection is confirmed, the game transitions to the multiplayer gameplay state.

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 to 127.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
Ensure both players are on the same network and the host’s firewall allows incoming connections on port 7777.

Troubleshooting

If connection fails:
  • Verify the server is running and in the HOSTING state
  • Check that SERVER_IP points to the correct host address
  • Ensure port 7777 is not blocked by firewall rules
  • Confirm ENet has been initialized before calling SetupClient()