c++ - Multiple client and single server handling -
will approach work?
i gonna present code in simplified form easier readability. trying implement multiple client/one tcp server.
my listener loop this(as thread) handles connections
void waitandacceptconnection(){ if(socket_temp = accept(sock_listen, (sockaddr*)&address, &addresssize)) { socketsmanager.push_back(socket_temp); currcount++; std::cout<<"\n connection found!"<<std::endl; send(socketsmanager[currcount], "welcome! have connected athena server", 46,null); // cond.notify_one(); //notify waiting thread } }
wherein have..
std::vector<socket> socketsmanager; //handles socket int currcount=-1; //keep track on number of connections
if client connected currcount increased one, in our case it's gonna currcount = 0
, socketsmanager[0]
store accept's return. if 1 connected currcount = 1
socketsmanager[1]
handler.
for sending , receiving data.
i gonna make loop continue on iterating check if there recv'd data(-1 or 0) every sockets being handled program.
void waitandacceptcommands(){ for(int = 0; i<= currcount;i++){ int result = recv(socketsmanager[i],&command,1,0); if(result ==-1){ } else if(result == 0){ } else{ //process commands } } }
main this
athena ath2; //instance of server std::cout<<"\n >waiting incoming connections..."<<std::endl; //listener thread, keep on looping std::thread connectionthread([&](){ while(1){ ath2.waitandacceptconnection(); } }); //handles inputs, keep on looping std::thread commandsthread([&](){ while(1){ ath2.waitandacceptcommands(); } }); connectionthread.join(); //stop commandsthread.join(); //stop
i gladly show rest of code in complete mess right now. wanted present idea if work , continue on it, if not reconsider method. plan on handling connections through timeouts
if ever have drop socket std::vector<socket> socketsmanager;
using remove. method? if not issues?
i see couple of problems you're doing:
- you're pushing socketsmanager vector indefinitely. won't long before run out of memory / file descriptors.
- protect access socketsmanager lock, else can have race condition.
one way use event loop:
- have 1 or more threads doing i/o.
- each i/o thread operates on list of open sockets.
- it uses select() or poll() figure out socket amongst set operating on has data available. invokes necessary callbacks data read.
- processing data handled worker threads. callback invoked 1 of worker thread processes data.
references: http://instagram-engineering.tumblr.com/post/121930298932/c-futures-at-instagram (see non-blocking io section)
Comments
Post a Comment