#define BUF_SIZE 32768 #define PORT 1145 #include “socket.cpp”
#define addr first #define peer second.first #define player second.second
string ip; vector<pair<string, pair<int, int>>> iponline; map<int, queue<string>> msg;
struct SI { SocketTCP *s; int *n; }; DWORD WINAPI SendQueue(LPVOID lpPara) { SocketTCP s; SI si = *(SI *)lpPara; s = *si.s; int n = *si.n; while (1) { if (msg[n].size()) { cout << “Send command ” << “PEER ” + msg[n].front() << ” to client.” << endl; s.aSend(“PEER ” + msg[n].front()); msg[n].pop(); } } } DWORD WINAPI Talk(LPVOID lpParameter) { SocketTCP s; s = *(SocketTCP *)lpParameter; int n = 0; while (1) { string r = s.aRecv(); if (r == “ONLINE”) { n = iponline.size(); iponline.push_back(make_pair((string)inet_ntoa(s.aGetTargetAddress().sin_addr), make_pair(n, 0))); s.aSend(to_string(n)); SI si; si.s = &s; si.n = &n; CreateThread(NULL, 0, SendQueue, (LPVOID)(&si), 0, NULL); } else if (r == “FIND”) { if (iponline[n].peer == n || iponline[iponline[n].peer].player == 0) for (int i = 0; i < iponline.size(); i++) { if (i == n || iponline[i].player == -1) { continue; } if (iponline[i].peer == i) { iponline[i].peer = n; iponline[n].peer = i; iponline[i].player = 1; iponline[n].player = 2; break; } } if (iponline[n].peer == n) { s.aSend(“NOPE”); } else { s.aSend(to_string(iponline[n].peer) + ” ” + to_string(iponline[n].player)); } } else if (r == “REFIND”) { for (int i = 0; i < iponline.size(); i++) { if (i == n || iponline[i].player == -1) { continue; } if (iponline[i].player == 0) { iponline[i].peer = n; iponline[n].peer = i; iponline[i].player = 1; iponline[n].player = 2; break; } } if (iponline[n].player == 0) { s.aSend(“NOPE”); } else { s.aSend(to_string(iponline[n].peer) + ” ” + to_string(iponline[n].player)); } } else if (r != "") { cout << “Push command ” << r << ” to peer queue.” << endl; msg[iponline[n].peer].push(r); } else { cout << “Curr leaves.” << endl; cout << “Push command LEAVE to peer queue.” << endl; msg[iponline[n].peer].push(“LEAVE”); iponline[n].player = -1; iponline[iponline[n].peer].player = 0; while (1); } } }
int main() { ios::sync_with_stdio(false); cout.tie(0); WSADATA wsd; WSAStartup(MAKEWORD(2, 2), &wsd); vector<string> vip = GetLocalIP(); WSACleanup(); cout << “IP address:” << endl; for (int i = 0; i < vip.size(); i++) { cout << i + 1 << ”:\t” << vip[i] << endl; } if (vip.size() == 1) { ip = vip[0]; } else { cout << “Choose an IP address to bind: ”; int x; cin >> x; while (x < 1 || x > vip.size()) { cout << “Error input number must bigger than 0 and smaller than ” << vip.size() + 1 << endl; cout << “Reinput IP address number: ”; cin >> x; } ip = vip[x - 1]; } SocketTCP s; s.sSetAddress(ip, PORT); s.sBind(); s.sListen(50); while (1) { s.sAccept(); cout << “Create thread for ” << inet_ntoa(s.aGetTargetAddress().sin_addr) << endl; CreateThread(NULL, 0, Talk, (LPVOID)(&s), 0, NULL); } }