生成一个简单的c++服务器例子
时间: 2024-05-03 19:19:43 浏览: 10
好的,以下是一个简单的 C++ 服务器例子:
```c++
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int server_socket, client_socket;
struct sockaddr_in server_address, client_address;
char buffer[1024] = {0};
const char *message = "Hello from server!";
// 创建 socket
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
std::cerr << "Failed to create socket" << std::endl;
return -1;
}
// 设置服务器地址
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(8888);
// 绑定 socket
if (bind(server_socket, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
std::cerr << "Failed to bind socket" << std::endl;
return -1;
}
// 监听 socket
if (listen(server_socket, 3) < 0) {
std::cerr << "Failed to listen on socket" << std::endl;
return -1;
}
std::cout << "Server listening on port 8888" << std::endl;
// 接受客户端连接
socklen_t client_address_size = sizeof(client_address);
if ((client_socket = accept(server_socket, (struct sockaddr *)&client_address, &client_address_size)) < 0) {
std::cerr << "Failed to accept client connection" << std::endl;
return -1;
}
std::cout << "Client connected" << std::endl;
// 从客户端接收数据
int bytes_received = read(client_socket, buffer, 1024);
std::cout << "Received " << bytes_received << " bytes from client: " << buffer << std::endl;
// 发送数据给客户端
send(client_socket, message, strlen(message), 0);
std::cout << "Sent message to client: " << message << std::endl;
// 关闭 socket
close(client_socket);
close(server_socket);
return 0;
}
```
这个例子实现了一个简单的服务器,它监听本地主机的 8888 端口,接受客户端连接,从客户端接收数据并且发送一条消息给客户端。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)