Secondo me, anche per separare le varie sezioni, ti conviene usare un pò di multithreading. Ovvero, ti fai una bella struct che comprende un thread ed un socket (ed anche un nome magari). Poi metti un thread che sta sempre in listen ed avvia gli altri thread di comunicazione man mano che i client fanno richieste. Così hai un programma un pò più strutturato e gestibile (IMHO).
Per capirci, tipo così:
Fondamentalmente è molto simile al codice di suomi, però fatto coi threadcodice:#define WINDOWS_LEAN_AND_MEAN #include <windows.h> #include "winsock2.h" using namespace std; struct client { char ID[20]; SOCKET sock; HANDLE Thread; } clients[80]; int FindFirstFree() { for(int i = 0; i < 80; i++) { if (!clients[i].sock) return i; } } #include <time.h> char *GiveID() { srand(time(0) + clock()); char *result = new char[20]; for (int i = 0; i < 19; i++) result[i] = rand()%26 + 65; result[19] = '\0'; return result; /*Come esempio ho messo un generatore di stringhe random, ma puoi metterci qualunque cosa*/ } SOCKET listening, incoming; bool uscita = false; // Quando vuoi uscire, setti questa variabile a 1 DWORD ClientThread(int c); DWORD Listening(LPDWORD NotUsed) { listening = socket(AF_INET, SOCK_STREAM, 0); sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(4015); addr.sin_addr.s_addr = inet_addr("127.0.0.1"); bind(listening, (SOCKADDR*)&addr, sizeof(addr)); listen(listening, 10); incoming = SOCKET_ERROR; while(1) { incoming = accept(listening, NULL, NULL); if (incoming != SOCKET_ERROR) { int c = FindFirstFree(); strcpy(clients[c].ID, GiveID()); clients[c].sock = incoming; clients[c].Thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) ClientThread(c), NULL, 0, NULL); } } } DWORD ClientThread(int c) { //Qui fai quello che vuoi col tuo client ! Il valore c, passato alla funzione ti indica chi è il client di questo thread. } int main() { WSADATA wsadata; WSAStartup(MAKEWORD(2,2), &wsadata); CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Listening, NULL, 0, NULL); while(!uscita); WSACleanup(); }.

.
Rispondi quotando