Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does C++ realize the function of chat room in Window environment

2025-04-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report