I'm developing a client/server for a simple game I'm making, but I have no clue on how to handle several clients?
I've read a few threads here and there with the same issue, but no "solve" was posted when solved.
Here we have the server
#include <iostream>
#include <enet/enet.h>
int main(int argc, char** argv) {
ENetAddress address;
ENetHost* server;
if (enet_initialize() != 0) {
fprintf(stderr, "Failed to initialize ENet!\n");
exit(-1);
}
// Bind the server to default localhost
// Specified host address can be specified by
// enet_address_set_host(&address, "x.x.x.x");
address.host = ENET_HOST_ANY;
// Bind the server to port 1234
address.port = 8484;
server = enet_host_create(&address /* the address to bind the server host to */,
32 /* allow up to 32 clients and/or outgoing connections */,
2 /* allow up to 2 channels to be used, 0 and 1 */,
0 /* assume any amount of incoming bandwidth */,
0 /* assume any amount of outgoing bandwidth */);
if (server == NULL)
{
fprintf(stderr,
"An error occurred while trying to create an ENet server host.\n");
exit(EXIT_FAILURE);
}
else {
std::cout << "MSC++Server has started" << std::endl << "Listening on IP: " << address.host << " Port: " << address.port << "." << std::endl;
}
ENetEvent event;
while (true) {
/* Wait up to 1000 milliseconds for an event. */
while (enet_host_service(server, &event, 1000) > 0)
{
switch (event.type)
{
case ENET_EVENT_TYPE_CONNECT:
printf("New connection from %x:%u.\n",
event.peer->address.host,
event.peer->address.port);
/* Store any relevant client information here. */
event.peer->data = "Client";
break;
case ENET_EVENT_TYPE_RECEIVE:
printf("A packet of length %u containing %s was received from %s on channel %u.\n",
(unsigned int)event.packet->dataLength,
event.packet->data,
event.peer->data,
event.channelID);
/* Clean up the packet now that we're done using it. */
enet_packet_destroy(event.packet);
break;
case ENET_EVENT_TYPE_DISCONNECT:
printf("%s disconnected.\n", event.peer->data);
/* Reset the peer's client information. */
event.peer->data = NULL;
}
}
}
atexit(enet_deinitialize);
}
This particular code especially
case ENET_EVENT_TYPE_CONNECT:
printf("New connection from %x:%u.\n",
event.peer->address.host,
event.peer->address.port);
/* Store any relevant client information here. */
event.peer->data = "Client";
break;
I have a "peer" or client if you will, with some data.
This connection is a single connection that can be established to the server, meaning if I instance a new client, the first client will have it's data overwritten.
How do I overcome this issue?