使用多线程,但是接收客户端的数据有问题,只能接收到一个客户端的,多开几个客户端就接受不到数据,但是发送数据全部客户端都可以接收到,估计是recv阻塞
下面附上代码
下面附上代码
#include<iostream> #include<cstdlib> #include <vector> #include <iterator> #include<winsock2.h> #pragma comment( lib, "ws2_32.lib" )// 链接Winsock2.h的静态库文件 using namespace std; DWORD WINAPI server_receive_thread(LPVOID lp);//接收信息线程函数 DWORD WINAPI server_send_thread(LPVOID lp);//发送信息线程函数 vector <SOCKET> clientSocketGroup; int main() { WSADATA wsa; /*初始化socket资源*/ if (WSAStartup(MAKEWORD(1, 1), &wsa) != 0) { cout << "Winsock库加载失败" << endl; return 0; //代表失败 } else { cout << "Winsock库加载成功" << endl; } SOCKET Sock_Server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); SOCKADDR_IN addSrv; addSrv.sin_family = AF_INET; //family是地址家族 通常大多用的是都是AF_INET,代表TCP/IP协议族 addSrv.sin_port = htons(3456); addSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); bind(Sock_Server, (sockaddr*)&addSrv, sizeof(addSrv)); listen(Sock_Server, 20); while (1) { sockaddr_in addClient; int len = sizeof(addClient); SOCKET sockConn = accept(Sock_Server, (SOCKADDR*)&addClient, &len); cout << "接收到连接" << endl; clientSocketGroup.push_back(sockConn); HANDLE hThread1; hThread1 = CreateThread(NULL, 0, server_send_thread, NULL, 0, NULL); LPVOID* lp = (LPVOID*)&sockConn; HANDLE hThread2; hThread2 = CreateThread(NULL, 0, server_receive_thread, lp, 0, NULL); } closesocket(Sock_Server); //closesocket(sockConn); WSACleanup(); return 0; system("pause"); } DWORD WINAPI server_send_thread(LPVOID lp) { const int BUF_SIZE = 64; char buff[BUF_SIZE]; char sendbuf[256]; while (1) { cin >> buff; memset(sendbuf, 0, sizeof(sendbuf)); strcpy(sendbuf, "admin"); strcat(sendbuf, "说:"); strcat(sendbuf, buff); for(int i = 0; i < clientSocketGroup.size(); ++i) { send(clientSocketGroup[i], sendbuf, 256, 0); // 发送信息 } } return 0; } DWORD WINAPI server_receive_thread(LPVOID lp) { SOCKET *s = (SOCKET *)lp; while (1) { const int BUF_SIZE = 256; char buf[BUF_SIZE]="0"; recv(*s, buf,BUF_SIZE, 0); if (buf[0] == "0") { break; } else { cout << buf << endl; for (int i = 0; i < clientSocketGroup.size(); ++i) { send(clientSocketGroup[i], buf, 256, 0); // 发送信息 } } buf[0] = "0"; } return 0; }
解决方案
20
你说的问题是原因是你把局部变量SOCKET的地址传给线程了,改成下面这样,线程执行后用delete去释放
SOCKET* lp = new SOCKET(sockConn);
你的代码还有其它的问题,创建这么多发送线程做什么?一个不就够了?