C++ sokect服务端
时间: 2023-07-03 21:06:35 浏览: 176
以下是一个简单的 C++ socket 服务器端程序:
```c++
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstring>
using namespace std;
int main() {
// 创建 socket
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1) {
cout << "Failed to create socket." << endl;
return 1;
}
// 绑定地址和端口
sockaddr_in server_address{};
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(8888);
if (bind(server_fd, (sockaddr *) &server_address, sizeof(server_address)) == -1) {
cout << "Failed to bind address and port." << endl;
return 1;
}
// 监听连接请求
if (listen(server_fd, 10) == -1) {
cout << "Failed to listen for connections." << endl;
return 1;
}
// 接受连接请求
sockaddr_in client_address{};
socklen_t client_address_len = sizeof(client_address);
int client_fd = accept(server_fd, (sockaddr *) &client_address, &client_address_len);
if (client_fd == -1) {
cout << "Failed to accept connection." << endl;
return 1;
}
// 读取数据
char buffer[1024];
ssize_t num_read = read(client_fd, buffer, sizeof(buffer)-1);
if (num_read == -1) {
cout << "Failed to read from client." << endl;
return 1;
}
buffer[num_read] = '\0';
cout << "Received message: " << buffer << endl;
// 发送数据
const char *response = "Hello from server!";
ssize_t num_sent = send(client_fd, response, strlen(response), 0);
if (num_sent == -1) {
cout << "Failed to send response to client." << endl;
return 1;
}
// 关闭连接
close(client_fd);
close(server_fd);
return 0;
}
```
该程序创建了一个监听在本地 8888 端口的 socket 服务器,可以接受客户端的连接请求,读取客户端发送的数据,并向客户端发送回应。但是该程序还不够完整和健壮,需要根据实际需求进行修改和优化。
阅读全文