C++ socket 多客户端连接
程序员文章站
2024-03-23 09:53:10
...
服务端
#include <stdio.h>
#include <winsock2.h>
#include <iostream>
#pragma comment (lib, "ws2_32.lib") //加载 ws2_32.dll
using namespace std;
DWORD WINAPI ServerThread(LPVOID lpParameter)
{
SOCKET ClientSocket = *(SOCKET*)lpParameter;
char serverBuffer[100] = { 0 };//缓冲区
while (1)
{
//客户端CloseSocket时,服务端recv()返回-1
if (recv(ClientSocket, serverBuffer, sizeof(serverBuffer), 0) == -1)
{
break;
}
send(ClientSocket, serverBuffer, sizeof(serverBuffer), 0);
memset(serverBuffer, 0, sizeof(serverBuffer)); //重置缓冲区
}
//关闭监听套接字
closesocket(ClientSocket);
return 0;
}
int main() {
//初始化 DLL
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
//创建套接字
SOCKET servSockToListen = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
//绑定套接字
sockaddr_in sockAddr;
memset(&sockAddr, 0, sizeof(sockAddr)); //每个字节都用0填充
sockAddr.sin_family = PF_INET; //使用IPv4地址
sockAddr.sin_addr.s_addr = htonl(INADDR_ANY); //具体的IP地址
sockAddr.sin_port = htons(9999); //端口
bind(servSockToListen, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR));
//设置监听状态
listen(servSockToListen, 20);
while(1)
{
//接收客户端请求
SOCKADDR clntAddr;
int nSize = sizeof(SOCKADDR);
//accept阻塞
SOCKET clntSock = accept(servSockToListen, (SOCKADDR*)&clntAddr, &nSize);
cout << "一个客户端已连接到服务器,socket是:" << clntSock << endl;
//为每一个线程创建一个线程
CreateThread(NULL, 0, &ServerThread, &clntSock, 0, NULL);
}
//关闭监听套接字
closesocket(servSockToListen);
//终止 DLL 的使用
WSACleanup();
return 0;
}
客户端
#include <stdio.h>
#include <winsock2.h>
#include <iostream>
#pragma comment (lib, "ws2_32.lib") //加载 ws2_32.dll
using namespace std;
int main() {
//初始化 DLL
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
//创建套接字
SOCKET servSockToContect = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
//绑定套接字
sockaddr_in sockAddr;
memset(&sockAddr, 0, sizeof(sockAddr));
sockAddr.sin_family = PF_INET;
sockAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
sockAddr.sin_port = htons(9999);
//connect阻塞
connect(servSockToContect, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR));
char sendBuffer[100] = { 0 };
char clientBuffer[100] = { 0 };
while (1)
{
cout << "请输入要发送的信息,按回车结束发送:" << endl;
cin.getline(sendBuffer, sizeof(sendBuffer));
if (strcmp(sendBuffer, "off") == 0)
{
break;
}
send(servSockToContect, sendBuffer, sizeof(sendBuffer), 0);
recv(servSockToContect, clientBuffer, sizeof(clientBuffer), 0);
cout << clientBuffer << endl;
memset(sendBuffer, 0, sizeof(sendBuffer)); //重置缓冲区
memset(clientBuffer, 0, sizeof(clientBuffer)); //重置缓冲区
}
//关闭套接字
closesocket(servSockToContect);
//终止 DLL 的使用
WSACleanup();
return 0;
}