C++使用多线程技术实现多客户端并发访问指定服务器Linux 客户端和服务端代码
时间: 2023-11-09 16:05:38 浏览: 102
客户端代码:
```c++
#include <iostream>
#include <string>
#include <thread>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
using namespace std;
void connect_server(int s)
{
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8888);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
while (connect(s, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1)
{
cout << "连接服务器失败!" << endl;
sleep(1);
}
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;
}
close(s);
}
int main()
{
int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
thread t(connect_server, s);
t.join();
return 0;
}
```
服务端代码:
```c++
#include <iostream>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
using namespace std;
int main()
{
int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8888);
server_addr.sin_addr.s_addr = INADDR_ANY;
bind(s, (struct sockaddr*)&server_addr, sizeof(server_addr));
listen(s, SOMAXCONN);
cout << "等待客户端连接..." << endl;
while (true)
{
int 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);
close(client_s);
cout << "客户端已断开连接!" << endl;
}
close(s);
return 0;
}
```
阅读全文