How does C++ realize the function of chat room in Window environment
This article introduces the knowledge of "how C++ realizes the function of chat room in Window environment". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Server side
According to the above, what a server needs to do:
① accepts new client connection requests
② listens to new messages from each connected client
③ transmits the received information to each connected server one by one.
Therefore, I set the server to have two threads, one thread responsible for the ① function and the other thread responsible for the ②③ function. (note: here I use to forward the message as soon as it is received, but there is no container to save it. Leakage may occur in the high concurrency phase).
① creates a thread that listens to client connection requests
Void CreateListenThread (int sock_serve,list*users) {sockaddr_in user_addr; int user_size = sizeof (user_addr); / / Loop accepts while (1) {/ / suspend 100ms per cycle, which takes up a lot of cpu this_thread::sleep_for (chrono::milliseconds (100)); int user_sock = accept (sock_serve, (sockaddr*) (& user_addr), & user_size) If (user_sock==-1) {/ / indicates that there is no connection continue;} if (username socksand inactive socket) {lock_guardmtx_locker (mtx); (* users) .push_back (user_sock); cout