C++使用多线程技术实现多客户端并发访问指定服务器 客户端和服务端代码
时间: 2023-09-14 14:15:58 浏览: 101
客户端代码:
```c++
#include <iostream>
#include <string>
#include <thread>
#include <winsock2.h>
using namespace std;
#pragma comment(lib,"ws2_32.lib")
void connect_server(SOCKET& s)
{
SOCKADDR_IN server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8888);
server_addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
while (connect(s, (SOCKADDR*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR)
{
cout << "连接服务器失败!" << endl;
Sleep(1000);
}
cout << "连接服务器成功!" << endl;
while (true)
{
string send_buf;
cout << "请输入要发送的内容:";
getline(cin, send_buf);
if (send_buf == "exit")
{
break;
}
send(s, send_buf.c_str(), send_buf.size(), 0);
char recv_buf[1024] = {0};
recv(s, recv_buf, sizeof(recv_buf), 0);
cout << "服务器返回:" << recv_buf << endl;
}
closesocket(s);
WSACleanup();
}
int main()
{
WSADATA wsa_data;
WSAStartup(MAKEWORD(2, 2), &wsa_data);
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
thread t(connect_server, s);
t.join();
return 0;
}
```
服务端代码:
```c++
#include <iostream>
#include <winsock2.h>
using namespace std;
#pragma comment(lib,"ws2_32.lib")
int main()
{
WSADATA wsa_data;
WSAStartup(MAKEWORD(2, 2), &wsa_data);
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8888);
server_addr.sin_addr.S_un.S_addr = INADDR_ANY;
bind(s, (SOCKADDR*)&server_addr, sizeof(server_addr));
listen(s, SOMAXCONN);
cout << "等待客户端连接..." << endl;
while (true)
{
SOCKET client_s = accept(s, NULL, NULL);
cout << "客户端已连接!" << endl;
char buf[1024] = { 0 };
recv(client_s, buf, sizeof(buf), 0);
cout << "收到客户端消息:" << buf << endl;
send(client_s, buf, strlen(buf), 0);
closesocket(client_s);
cout << "客户端已断开连接!" << endl;
}
closesocket(s);
WSACleanup();
return 0;
}
```
阅读全文