Server fails while posting to socket
Hello All!
I am trying to implement a multithreaded chat/quiz server using posix threads. The server is intended to run under UNIX platform
I am expecting a problem, while client tries to write data into the socket. Client part goes down immediately, however the server continues its work being in active loop and serving client requests.
All files are compiled with GNU C++ compiler and it seems the compilation phase goes well. At least, i can't notice any error.
I tend to think, that the problem occurs in this piece of code...
Code:
try {
while ((recvMsgSize = (*sock >> echoBuffer)) > 0) {
cout << client << ": " << echoBuffer << endl;
game->Receive(sock, echoBuffer);
}
}
...because, if i comment this line out "game->Receive(sock, echoBuffer);" the problem dissapears. Consequently, the error may hide in sendAll which is called out by Receive().
Server code
Code:
...
#include "QuizGameEngine.h"
...
//
// Client handling
//
void HandleClient(TCPSocket *sock) {
// Add client connection to the list
pthread_mutex_lock(&mutx);
c_connections.push_back(sock);
pthread_mutex_unlock(&mutx);
cout << "Handling client ";
try {
cout << sock->getForeignAddress() << ":";
}
catch (SocketException) {
cerr << "Unable to get foreign address" << endl;
}
try {
cout << sock->getForeignPort();
}
catch (SocketException) {
cerr << "Unable to get foreign port" << endl;
}
pthread_t client;
cout << " with thread " << client << endl;
string echoBuffer;
int recvMsgSize;
try {
while ((recvMsgSize = (*sock >> echoBuffer)) > 0) {
cout << client << ": " << echoBuffer << endl;
game->Receive(sock, echoBuffer);
}
}
catch (SocketException) {
cout << client << " has left the server." << endl;
}
// Remove client connection and Player from the list
pthread_mutex_lock(&mutx);
game->RemovePlayer(sock);
c_connections.remove(sock);
pthread_mutex_unlock(&mutx);
}
GameEngine -- header file, containing all the functions to interact wit server part
Code:
...
class QuizGameEngine {
...
void Receive(TCPSocket *sock, string input) {
//ParseInput(sock, input);
SendAll(input);
}
/* First word is not a command, execute input */
//ExecuteInput(sock, input);
SendAll(input);
}
void SendTo(TCPSocket *sockIt, string msg) {
*sockIt << msg;
}
void SendAll(string msg) {
for (socket_list::iterator
sockIt = sockets->begin();
sockIt != sockets->end();
sockIt++) {
SendTo((TCPSocket *)&sockIt, msg);
}
}
void SendAllExcept(TCPSocket *sockNot, string msg) {
for (socket_list::iterator
sockIt = sockets->begin();
sockIt != sockets->end();
sockIt++) {
if ((TCPSocket *)&sockIt != sockNot) {
SendTo((TCPSocket *)&sockIt, msg);
}
}
}
};
I also don't think problem may be in client, it's rather in a sending procedure. Additionally, client part of code, does not have a deal with a GameEngine
Hope to get an answer to my issue
Thank you!