windows socket 服务端使用线程连接多个客户端
server
//用线程处理一个客户端的收发信息 DWORD WINAPI ThreadFunc04(LPVOID params) { SOCKET skt = (SOCKET)params; sockaddr_in addr = {0}; int addrLen = sizeof(addr); getpeername(skt, (sockaddr *)&addr, &addrLen);//获取套接字的信息 char buf[1024]; int ret; while (true) { ret = recv(skt, buf, sizeof(buf), 0); if (ret == SOCKET_ERROR) { printf("[server] recv socket:%d ip:%s port:%d error ...\n", skt, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port)); break; } if (ret == 0) { printf("[client] socket:%d ip:%s port:%d exit ...\n", skt, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port)); break; } printf("[client] socket:%d ip:%s port:%d\n", skt, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port)); printf("[client] msg: %s\n", buf); if (strcmp(buf, "getName") == 0) { sprintf(buf, "%s", "爱白菜的小昆虫."); } else if (strcmp(buf, "getAge") == 0) { sprintf(buf, "%s", "100000."); } else { sprintf(buf, "%s", "????."); } send(skt, buf, strlen(buf)+1, 0); } return 0; } //服务端 使用线程连接多个客户端 int function04() { SOCKET sktServ = init("0.0.0.0", 8080); if (sktServ == INVALID_SOCKET) { return -1; } DWORD threadId; SOCKET sktCli = INVALID_SOCKET; sockaddr_in addr = { 0 }; int addrLen = sizeof(addr); while (true) { sktCli = accept(sktServ, (sockaddr *)&addr, &addrLen); if (sktCli == INVALID_SOCKET) { printf("[client] accpet error ...\n"); return -1; } printf("[client] socket:%d ip:%s port:%d accept ...\n", sktCli, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port)); //创建线程 CreateThread(NULL, 0, ThreadFunc04, (LPVOID)sktCli, 0, &threadId); } destroy(sktServ); return 0; }
client
//客户端写数据
DWORD WINAPI ThreadFunc04(LPVOID params) {
SOCKET skt = (SOCKET)params;
int ret;
char buf[1024];
while (true) {
printf("*************************\n");
printf("*getName *\n");
printf("*getAge *\n");
printf("*exit *\n");
printf("*************************\n");
scanf("%s", buf);
if (strcmp(buf, "exit") == 0) {
break;
}
ret = send(skt, buf, strlen(buf)+1, 0);
if (ret == SOCKET_ERROR) {
printf("[client] send error ...\n");
return -1;
}
printf("[client] %s send success ...\n", buf);
ret = recv(skt, buf, sizeof(buf), 0);
if (ret == SOCKET_ERROR) {
printf("[client] recv error ...\n");
return -1;
}
if (ret == 0) {
printf("[client] server exit ...\n");
return -1;
}
printf("[server] msg: %s\n", buf);
}
return 0;
}
//socket客户端 使用线程接受和发送消息
int function04() {
SOCKET sktCli = init("192.168.3.18", 8080);
if (sktCli == INVALID_SOCKET) {
return -1;
}
HANDLE hThread;
DWORD exitCode;
DWORD threadId;
hThread = CreateThread(NULL, 0, ThreadFunc04, (LPVOID)sktCli, 0, &threadId);
while (true) {
GetExitCodeThread(hThread, &exitCode);//获取执行码
if (exitCode != STILL_ACTIVE) {//线程运行完
break;
}
Sleep(1000);
}
CloseHandle(hThread);
printf("ReadThreadFunc04 return %d\n", exitCode);
printf("[client] run end ...\n");
destroy(sktCli);
return 0;
}