本文主要是介绍C++ Socket 多线程 网络聊天室 支持用户端双向交流(2023),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.效果如下:
2.服务端代码 :
//服务端
#include <winsock2.h>
#include <iostream>
#include <list>#pragma comment(lib, "ws2_32.lib")
using namespace std;// 线程处理函数
DWORD WINAPI ThreadFun(LPVOID lpThreadParameter);void init_app();
void Send_All(list<SOCKET> Client_List_Now,char *msg,SOCKET This_Socket);
char* GetName(int num);WSADATA wd;
SOCKET Socket;
list<SOCKET> Client_List;
sockaddr_in addrClient;
int len = sizeof(sockaddr_in);int main() {init_app();//主线程循环接收客户端的连接while (true) {// 接受成功返回与client通讯的SocketSOCKET Client = accept(Socket, (SOCKADDR *) &addrClient, &len);if (Client!= INVALID_SOCKET) {// 创建线程,并且传入与client通讯的套接字HANDLE hThread = CreateThread(NULL, 0, ThreadFun, (LPVOID) Client, 0, NULL);CloseHandle(hThread); // 关闭对线程的引用}}//关闭监听套接字closesocket(Socket);//清理winsock2的环境WSACleanup();return 0;
}DWORD WINAPI ThreadFun(LPVOID lpThreadParameter) {// 接受数据SOCKET This_Socket = (SOCKET) lpThreadParameter;// 发送欢迎char buf[100] = {0};sprintf(buf, "********欢迎 %s 进入聊天室*******\n", GetName(This_Socket));cout <<This_Socket << "进入聊天室\n";Send_All(Client_List,buf,This_Socket);Client_List.push_back(This_Socket);// 循环接收客户端数据int ret = 0;do {char buf2[100] = {0};ret = recv(This_Socket,buf2, 100, 0);cout << This_Socket << "发送了:" << buf2 << endl;char str3[200];strcpy(str3, GetName(This_Socket));strcat(str3, "发送了:");strcat(str3, buf2);Send_All(Client_List,str3,This_Socket);} while (ret != SOCKET_ERROR && ret != 0);Client_List.remove(This_Socket);cout << This_Socket << "离开了聊天室\n";return 0;
}void Send_All(list<SOCKET> Client_List_Now,char *msg,SOCKET This_Socket)
{Client_List_Now.remove(This_Socket);for (auto iter : Client_List_Now){send(iter, msg, strlen(msg), 0);}
}void init_app() {cout<<"===========服务端============"<<endl;char falg;char *ip;if (WSAStartup(MAKEWORD(2, 2), &wd) != 0) {cout << "WSAStartup Error:" << WSAGetLastError() << endl;return;}// 创建流式套接字Socket= socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if (Socket == INVALID_SOCKET) {cout << "socket error:" << WSAGetLastError() << endl;return;}cout << "是否自定义当前服务器IP(y/n):";cin >> falg;switch (falg) {case 'n': {ip = "127.0.0.1";break;}case 'y': {cout << "请输入IP:";cin >> ip;break;}}//绑定端口和ipsockaddr_in addr;memset(&addr, 0, sizeof(sockaddr_in));addr.sin_family = AF_INET;addr.sin_port = htons(8000);addr.sin_addr.s_addr = inet_addr(ip);cout << "服务端IP:" << ip << "\n";//服务端bind绑定if (bind(Socket, (SOCKADDR *) &addr, len) == SOCKET_ERROR) {cout << "bind Error:" << WSAGetLastError() << endl;return;}// 监听20个以下设备listen(Socket, 20);
}
char* GetName(int num) {num=(num%19)+1;switch (num) {case (1) : {return "小张";}case (2) : {return "小林";}case (3) : {return "小江";}case (4) : {return "小刘";}case (5) : {return "小阮";}case (6) : {return "小夏";}case (7) : {return "小吉";}case (8) : {return "小李";}case (9) : {return "小黄";}case (10): {return "小谢";}case (11): {return "小傅";}case (12): {return "小洪";}case (13): {return "小荣";}case (14): {return "小吕";}case (15): {return "小方";}case (16): {return "小黎";}case (17): {return "小郑";}case (18): {return "小雷";}case (19): {return "小吴";}}
}
3.客户端代码:
#include<winsock2.h>//winsock2的头文件
#include<iostream>
#include <pthread.h>using namespace std;void init_app();void *GetMsg(void *socket);void SendMsg();#pragma comment(lib, "ws2_32.lib")WSADATA wd;
SOCKET Socket;
//客户端
int main() {init_app();//接收服务端的消息pthread_t tids;pthread_create(&tids, NULL, GetMsg, &Socket);//随时给服务端发消息SendMsg();//关闭监听套接字closesocket(Socket);//清理winsock2的环境WSACleanup();return 0;
}void SendMsg() {int ret = 0;do {char buf[100] = {0};cin >> buf;cout<<"你发送了:"<<buf<<endl;ret = send(Socket, buf, 100, 0);} while (ret != SOCKET_ERROR && ret != 0);
}void *GetMsg(void *socket) {do {int ret = 0;do {char buf2[100] = {0};ret = recv(Socket, buf2, 100, 0);cout << buf2 << endl;} while (ret != SOCKET_ERROR && ret != 0);} while (true);
}void init_app() {cout<<"===========客户端============"<<endl;//加载winsock2的环境if (WSAStartup(MAKEWORD(2, 2), &wd) != 0) {cout << "WSAStartup error:" << GetLastError() << endl;return;}//创建流式套接字Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if (Socket == INVALID_SOCKET) {cout << "socket error:" << GetLastError() << endl;return;}char falg;cout << "是否输入服务器IP(y/n):";cin >> falg;char *ip;switch (falg) {case 'n': {ip = "127.0.0.1";break;}case 'y': {cout << "请输入IP:";cin >> ip;break;}}//链接服务器sockaddr_in addr;addr.sin_family = AF_INET;addr.sin_port = htons(8000);addr.sin_addr.s_addr = inet_addr(ip);cout << "你的IP:" << ip << "\n";int len = sizeof(sockaddr_in);if (connect(Socket, (SOCKADDR *) &addr, len) == SOCKET_ERROR) {cout << "connect error:" << GetLastError() << endl;return;}
}
4.导入ws2_32库到Clion :
导入ws2_32库到Clion项目-CSDN博客
2024 HNUST计算机网络课程设计-(ᕑᗢᓫ∗)˒芒果酱-参考文章
(代码可以参考,૮₍ ˃ ⤙ ˂ ₎ა 但同学们要认真编写哦)
-------------------------------------------------------------------------
1、网络聊天程序的设计与实现
C++ Socket 多线程 网络聊天室 支持用户端双向交流(2023)-CSDN博客
2、Tracert 与 Ping 程序设计与实现
Tracert 与 Ping 程序设计与实现(2024)-CSDN博客
3、滑动窗口协议仿真
滑动窗口协议仿真(2024)-CSDN博客
4、OSPF 路由协议原型系统设计与实现
OSPF 路由协议原型系统设计与实现-CSDN博客
5、基于 IP 多播的网络会议程序
基于 IP 多播的网络会议程序(2024)-CSDN博客
6、编程模拟 NAT 网络地址转换
编程模拟 NAT 网络地址转换(2024)-CSDN博客
7、网络嗅探器的设计与实现
网络嗅探器的设计与实现(2024)-转载-CSDN博客
8、网络报文分析程序的设计与实现
网络报文分析程序的设计与实现(2024)-CSDN博客
9、简单 Web Server 程序的设计与实现
简单 Web Server 程序的设计与实现 (2024)-CSDN博客
10、路由器查表过程模拟计算机网络 - 路由器查表过程模拟 C++(2024)-CSDN博客
这篇关于C++ Socket 多线程 网络聊天室 支持用户端双向交流(2023)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!