用c++写一个异步的socket通讯
时间: 2023-12-03 07:03:12 浏览: 49
以下是使用 C++ 编写异步 Socket 通信的一个基本示例:
```cpp
#include <iostream>
#include <cstring>
#include <thread>
#include <chrono>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
using namespace std;
void worker(int sock) {
char buf[1024];
while (true) {
memset(buf, 0, sizeof(buf));
int len = recv(sock, buf, sizeof(buf), 0);
if (len > 0) {
cout << "Received message: " << buf << endl;
}
}
}
int main() {
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
cerr << "Failed to create socket." << endl;
return -1;
}
sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(12345);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sock, (sockaddr *) &addr, sizeof(addr)) < 0) {
cerr << "Failed to bind socket." << endl;
return -1;
}
if (listen(sock, 5) < 0) {
cerr << "Failed to listen on socket." << endl;
return -1;
}
while (true) {
sockaddr_in client_addr = {};
socklen_t client_addr_len = sizeof(client_addr);
int client_sock = accept(sock, (sockaddr *) &client_addr, &client_addr_len);
if (client_sock < 0) {
cerr << "Failed to accept client connection." << endl;
continue;
}
// 将客户端 socket 设置为非阻塞模式
int flags = fcntl(client_sock, F_GETFL, 0);
fcntl(client_sock, F_SETFL, flags | O_NONBLOCK);
thread t(worker, client_sock);
t.detach();
}
return 0;
}
```
上述代码中的 `worker` 函数是一个用于处理客户端 Socket 连接的线程函数,它会不断地接收客户端发来的消息并打印出来。
在 `main` 函数中,首先创建了一个 Socket 并绑定到本地的 12345 端口上,然后通过 `accept` 函数接收客户端连接,并将客户端 Socket 设置为非阻塞模式。最后,创建一个新的线程来处理客户端连接,并将该线程设为分离线程。
需要注意的是,异步 Socket 通信需要注意线程安全问题,需要使用线程锁或者原子操作等手段来保证多线程访问的安全性。此外,还需要处理异常情况,比如客户端 Socket 断开连接等。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)