1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
#include <enet\enet.h>
#include <iostream>
#include <allegro5\allegro.h>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
struct Players
{
float x;
float y;
int ID;
};
int main () {
bool done = false;
vector<ENetPeer*> peers;
vector<Players> players;
al_init();
enet_initialize();
ENetAddress address;
ENetHost * server;
ENetEvent event;
address.host = ENET_HOST_ANY;
address.port = 12345;
server = enet_host_create(&address, 32, 1, 0, 0);
ALLEGRO_TIMER *timer = NULL;
ALLEGRO_EVENT_QUEUE *event_queue = NULL;
timer = al_create_timer(1.0 / 60.0);
event_queue = al_create_event_queue ();
al_register_event_source(event_queue, al_get_timer_event_source(timer));
al_start_timer(timer);
while (!done) {
ALLEGRO_EVENT ev;
al_wait_for_event(event_queue, &ev);
while (enet_host_service (server, & event, 0) > 0) {
switch (event.type) {
case ENET_EVENT_TYPE_CONNECT:
{
printf ("A new client connected from %x:%u.\n", event.peer -> address.host, event.peer -> address.port);
event.peer -> data = "Client";
peers.push_back(event.peer);
char packet[256];
int newID = peers.size();
int packetlen = sprintf_s(packet, sizeof(packet), "P%i", newID);
ENetPacket *p = enet_packet_create((char*)packet, strlen(packet)+1, ENET_PACKET_FLAG_UNSEQUENCED);
printf("Sent a packet to server containing %s\n", packet);
printf("New Clients ID: %i", newID);
enet_peer_send(event.peer, 0, p);
}
break;
case ENET_EVENT_TYPE_RECEIVE:
{
if(event.packet->data[0] == 'P') {
char message[100];
int coordCount = 0;
int x;
int y;
for(unsigned int i = 1; i < event.packet->dataLength; ++i) {
message[i] = event.packet->data[i];
}
string coords = message;
coords.erase(0, 1);
istringstream ss(coords);
string token;
while(getline(ss, token, ',')) {
if (coordCount == 0) {
coordCount++;
x = atoi(token.c_str());
}
else if (coordCount == 1) {
y = atoi(token.c_str());
}
}
cout << "Player X: " << x << " Player Y: " << y << endl;
for (unsigned int i = 0; i < peers.size(); i++)
enet_peer_send(peers[0], 0, event.packet);
}
enet_packet_destroy (event.packet);
}
break;
case ENET_EVENT_TYPE_DISCONNECT:
printf ("%s disconected.\n", event.peer -> data);
event.peer -> data = NULL;
break;
}
}
}
enet_host_destroy(server);
}
|