C++ Chatroom
A chatroom written in C++

Description
This project was the exam assignment of the final programming class. Since I have always been interested in how networking works, I decided to make a chatroom for this free assignment. The program consists of a server and client build. Multiple clients can connect to the server at once and all conversations are recorded and saved in text-files in the server folder.
Code of the client.
bool ChatClient::ConnectServer(int portNumber, char* IP)
{
// Settings
SetClientSockAddr(&m_SockAddress, portNumber, IP);
if ((m_ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
cout << "ChatClient::ConnectServer could not create socket" << endl;
return false;
}
cout <<endl << "Attempting to connect to " << inet_ntoa(m_SockAddress.sin_addr) << endl<<endl;
if (connect(m_ListenSocket, reinterpret_cast<sockaddr*>(&m_SockAddress), sizeof(m_SockAddress)) != 0) // Connect to the server
{
cout<< "There is no server on this IP Address"<<endl;
return false;
}
return true;
}
unsigned __stdcall SendServerMessage(void *data)
{
while (true)
{
char *SendText = new char[256];
//cout << endl;
cout << "You: ";
cin.getline(SendText, 255, '\n');
if (strcmp(SendText, "exit") == 0)
{
return 7;
}
if (strcmp(SendText, " ") != 0)//if both strings are equal it returns 0 //add extra keywords if needed
{
if (send(reinterpret_cast<SOCKET>(data), SendText, strlen(SendText), 0) == SOCKET_ERROR)
{
cout << endl << "Server is down" << endl;
return 8;
}
}
delete[] SendText;
}
return 0;
}
Code of the server.
void ChatServer::LookForNewClients()
{
SOCKET clientSocket;
int clientIdLocal = 0;
while ((clientSocket=accept(m_ListenSocket,nullptr,nullptr)))
{
//create a new thread for each client
//the first message we get will contain the nickname of the client that connected
char Buffer[256];
int BytesRec = recv(clientSocket, Buffer, sizeof(Buffer), 0);
Buffer[BytesRec] = 0;
unsigned threadID;
Client c;
c.clientSocket= clientSocket;
c.nickName = Buffer;
c.clientId = clientIdLocal;
ClientList.push_back(c);
_beginthreadex(nullptr, 0, &ChatTest, reinterpret_cast<void*>(&ClientList[clientIdLocal]), 0, &threadID);
++clientIdLocal;
}
}