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
|
#include "includes.h"
DWORD WINAPI ls_Listen(LPVOID para) {
XServer::LoginServer *ls = (XServer::LoginServer *) para;
SOCKADDR_IN csin;
SOCKET csock;
int size = sizeof(csin);
int i;
int j;
int nbytes;
char* buf = NULL;
FD_ZERO(&ls->FD_Listen);
FD_SET(ls->sock, &ls->FD_Listen);
ls->FD_Max = ls->sock;
struct timeval tv;
tv.tv_sec = (time_t)0;
tv.tv_usec = (time_t)100;
for(;;) {
FD_ZERO(&ls->FD_tmp);
ls->FD_tmp = ls->FD_Listen;
if (select(ls->FD_Max+1, &ls->FD_tmp, NULL, NULL, &tv) < 0) {
cout << "ERROR: ls_Listen --> select() : " << WSAGetLastError() << endl;
break;
}
for(i = 0; i <= ls->FD_Max; ++i) {
if (FD_ISSET(i, &ls->FD_tmp)) {
if (i == ls->sock){
csock = accept(ls->sock, (SOCKADDR *) &csin, &size);
if(!ls->acceptingClients()) {
int a = CONNECT_REFUSED;
send(csock, (char*)&a, sizeof(int), 0);
shutdown(csock, 2);
}
else if(ls->getMaxClients() <= ls->nbClients()) {
int a = SERVER_FULL;
send(csock, (char*)&a, sizeof(int), 0);
shutdown(csock, 2);
}
else {
if(csock >= 0) {
FD_SET(csock, &ls->FD_Listen);
if(csock > ls->FD_Max) {
ls->FD_Max = csock;
}
printf("LoginServer: Client connection (IP: %s; Port: %d)\n", inet_ntoa(csin.sin_addr), ntohs(csin.sin_port));
/*Client *c = new Client((std::string)inet_ntoa(csin.sin_addr), (int)ntohs(csin.sin_port));
c->Sock(csock);
ls->AddClient(c);
Packet *p = new Packet();
p->setInfo(1, 0);
c->writePacket(p);*/
send(csock, "hello", 5, 0);
}
else {
cout << "shutdown" << endl;
shutdown(csock, 2);
}
}
}
else {
nbytes = recv(i, buf, sizeof(char*), 0);
cout << "nbytes: " << nbytes << endl;
if(nbytes > 0) {
// nbytes > 0
// buf à des donnees de i !
cout << "received buf: " << buf << endl;
Packet *p;
p = new Packet((std::string)buf);
ls->PacketHandler()->Push(p);
send(i, buf, nbytes, 0); // send back (test)
}
else if(nbytes <= 0) {
printf("LoginServer: Client disconnection (i=%d)", i);
shutdown(i, 2);
FD_CLR(i, &ls->FD_Listen);
}
else {
// client disconnection aswell ???
cout << "ERROR: ls_Listen --> recv() - " << nbytes << "/" << WSAGetLastError() << endl;
shutdown(i, 2);
FD_CLR(i, &ls->FD_Listen);
}
}
}
}
}
cout << "INFO: LoginServer stopped listening." << endl;
CloseHandle(ls->thread);
return 0;
}
|