diff --git a/TCP_Application/Main.cpp b/TCP_Application/Main.cpp index c385854..ef8c762 100644 --- a/TCP_Application/Main.cpp +++ b/TCP_Application/Main.cpp @@ -3,6 +3,9 @@ #include #include #include +#include +#include +#include #pragma warning(disable : 4996) //_CRT_SECURE_NO_WARNINGS #pragma comment(lib,"ws2_32.lib") @@ -15,6 +18,24 @@ SOCKET listener = INVALID_SOCKET; SOCKET client = INVALID_SOCKET; char recvbuf[DEFAULT_BUFLEN]; int recvbuflen = DEFAULT_BUFLEN; +std::map names; + +std::vector split(std::string txt) { + std::string buf = ""; + std::vector v; + bool first = true; + for (int i = 0; i < txt.length();i++) { + if (txt[i] == ' ') { + v.push_back(buf); + buf = ""; + } + else { + buf += txt[i]; + } + } + v.push_back(buf); + return v; +} int main() { wsRes = WSAStartup(MAKEWORD(2, 2), &wsaData); @@ -112,12 +133,55 @@ int main() { } else { std::cout << "Bytes recived: " << inBytes << std::endl; + if (buf[1] == '\\') { + + std::string cmd = std::string(buf, inBytes); + std::vector args = split(cmd); + if (args[0] == "\\\\help") { + std::string resp = "\\\\name - Set nickname\r\n"; + send(s, resp.c_str(), resp.size(), 0); + continue; + } + if (args[0] == "\\\\name") { + std::cout << args.size(); + if (args.size() == 1) { + std::string resp = "Too few arguments!\r\n"; + send(s, resp.c_str(), resp.size(),0); + continue; + } + if (args.size() > 2) { + std::string resp = "Too many arguments!\r\n"; + send(s, resp.c_str(), resp.size(), 0); + continue; + } + if (names.find(s) == names.end()) { + names.insert(std::make_pair(s, args[1])); + } + else { + names[s] = args[1]; + } + + std::cout << "Socket #" << s << " set it's name to " << args[1] << std::endl; + std::string resp = "Name change successful!\r\n"; + send(s, resp.c_str(), resp.size(), 0); + continue; + } + + //Unknown command! + std::string resp = "Unknown command!\r\n"; + resp += args[0]; + send(s, resp.c_str(), resp.size(), 0); + continue; + } + else std::cout << buf[0]; for (int j = 0; j < master.fd_count;j++) { SOCKET outSock = master.fd_array[j]; if (outSock != listener && outSock != s) { std::ostringstream sst; - sst << "SOCKET #" << s << " : " << buf << std::endl; + std::ostringstream k; + k << "SOCKET #"<< s; + sst << ( ( names.find(s) != names.end()) ? names[s] : k.str()) << " : " << buf << std::endl; std::string msg = sst.str(); std::cout << msg; send(outSock, msg.c_str(), msg.size() + 1, 0);