Reputation: 431
I am trying to create program,which hosts a server and lets multiple clients to join a server.I am able to create server socket,which allows only one connection,but I am unable to adapt my multithreading knowledge to it.My code throws runtime error whenever client connects(when creating new thread).There is my code: int result; int recvbuf; int dataReceived;
int save(int key_stroke,char *file);
class ClientHandler{
public:
void operator()(SOCKET s){
try{
do{
result = recv(s,(char*)&recvbuf,4,0);
dataReceived = ntohl(recvbuf);
if(result>0){
save(dataReceived,"log.txt");
}else{
cout << "CONNECTION LOST!" << endl;
}
}while(result > 0);
}catch(...){}
}
};
int main()
{
WSAData wsa;
WORD version = MAKEWORD(2,1);
WSAStartup(version, &wsa);
SOCKET Listener = socket(AF_INET,SOCK_STREAM,NULL);
SOCKET Connect = socket(AF_INET,SOCK_STREAM,NULL);
SOCKADDR_IN Server;
Server.sin_addr.s_addr = INADDR_ANY;
Server.sin_family = AF_INET;
Server.sin_port = htons(5125);
int sizeOf = sizeof(Server);
bind(Listener, (SOCKADDR*)&Server , sizeOf);
listen(Listener,100);
cout << "Listening" << endl;
for(;;){
Connect = accept(Listener,(SOCKADDR*)&Server , &sizeOf);
cout << "CONNECTION MADE!" << endl;
thread t1((ClientHandler()) ,Connect);
}
}
Upvotes: 3
Views: 6634
Reputation: 698
Since you are using C++ Socket Programming, you maybe want to use the QT C++ library. It is free, open source and have most problems allready solved and a good, very well documented api:
http://qt-project.org/doc/qt-5/qtnetwork-threadedfortuneserver-example.html
All examples: http://qt-project.org/doc/qt-5/examples-network.html
Upvotes: 0
Reputation: 303656
That's because you're deleting your thread as soon as you create it. You need to save them somewhere:
std::vector<std::unique_ptr<std::thread>> threads;
for (;;) {
// as before
threads.emplace_back(new std::thread((ClientHandler()), Connect));
}
Upvotes: 3