C++等待socket回复
时间: 2023-09-11 09:13:16 浏览: 66
在C++中,你可以使用套接字编程来等待套接字的回复。以下是一个简单的示例代码,演示如何等待套接字的回复:
```cpp
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
// 创建套接字
int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == -1) {
std::cerr << "无法创建套接字" << std::endl;
return 1;
}
// 定义服务器地址
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(8080); // 替换为你的服务器端口号
serverAddress.sin_addr.s_addr = INADDR_ANY;
// 绑定套接字到服务器地址
if (bind(serverSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) == -1) {
std::cerr << "绑定套接字失败" << std::endl;
close(serverSocket);
return 1;
}
// 监听套接字
if (listen(serverSocket, 5) == -1) {
std::cerr << "监听套接字失败" << std::endl;
close(serverSocket);
return 1;
}
std::cout << "等待客户端连接..." << std::endl;
// 接受客户端连接
int clientSocket = accept(serverSocket, NULL, NULL);
if (clientSocket == -1) {
std::cerr << "无法接受客户端连接" << std::endl;
close(serverSocket);
return 1;
}
std::cout << "客户端已连接" << std::endl;
// 接收客户端消息
char buffer[1024];
int bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0);
if (bytesRead == -1) {
std::cerr << "接收消息失败" << std::endl;
close(clientSocket);
close(serverSocket);
return 1;
}
std::cout << "收到消息: " << buffer << std::endl;
// 发送回复给客户端
阅读全文