How to use C++ to realize the function of chat room in Window environment
This article mainly introduces "how to use C++ to achieve the function of chat room in Window environment". In daily operation, I believe many people have doubts about how to use C++ to achieve the function of chat room in Window environment. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "how to use C++ to achieve the function of chat room in Window environment". Next, please follow the editor to study!
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