I am trying to make a multiplayer 2d shooter game using Enet. I wanted to test its networking capabilities with a friend. It uses a hybrid p2p and p2c architecture (A player can host a game, kinda like LAN worlds in minecraft, if you know what I mean). He gave me his IP and I tried to join his hosted game but my client couldn't connect.
I tried looking at how assault cube does its networking, but I found no answer.
This is how I connect:
bool connectToServer(ENetHost *&client, ENetPeer *&server, int32_t &cid, std::string ip, char *playerName)
{
ENetAddress adress;
ENetEvent event;
if (ip.empty())
{
enet_address_set_host(&adress, "127.0.0.1");
}
else
{
enet_address_set_host(&adress, ip.c_str());
}
//enet_address_set_host(&adress, "95.76.249.14");
//enet_address_set_host(&adress, "192.168.1.11");
adress.port = 7778;
//client, adress, channels, data to send rightAway
server = enet_host_connect(client, &adress, SERVER_CHANNELS, 0);
if (server == nullptr)
{
return false;
}
//see if we got events by server
//client, event, ms to wait(0 means that we don't wait)
if (enet_host_service(client, &event, 5000) > 0
&& event.type == ENET_EVENT_TYPE_CONNECT)
{
std::cout << "connected\n";
}
else
{
enet_peer_reset(server);
return false;
}
if (enet_host_service(client, &event, 5000) > 0
&& event.type == ENET_EVENT_TYPE_RECEIVE)
{
Packet p = {};
size_t size;
auto data = parsePacket(event, p, size);
// Handshake
if (p.header != headerReceiveCIDAndData)
{
enet_peer_reset(server);
return false;
}
cid = p.cid;
glm::vec3 color = *(glm::vec3 *)data;
auto e = phisics::Entity();
e.pos = getSpawnPosition();
e.lastPos = e.pos;
e.color = color;
memcpy(e.name, playerName, playerNameSize);
players[cid] = e;
sendPlayerData(e, true);
std::cout << "received cid: " << cid << "\n";
enet_packet_destroy(event.packet);
return true;
}
else
{
enet_peer_reset(server);
return 0;
}
return true;
}