使用c++实现一个tcp socket的服务端程序,实现一下功能:1、在某一个接口内服务端能够接收客户端的请求信息 2、将接收的请求信息传参传出
时间: 2024-02-03 16:13:40 浏览: 63
以下是一个简单的C++ TCP Socket服务端程序,可以实现接收客户端请求信息,并将信息打印出来。
```c++
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
int main()
{
// 创建socket
int server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (server_socket == -1)
{
std::cerr << "Failed to create socket!" << std::endl;
return -1;
}
// 绑定地址和端口
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(8888);
if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1)
{
std::cerr << "Failed to bind address and port!" << std::endl;
close(server_socket);
return -1;
}
// 监听端口
if (listen(server_socket, 10) == -1)
{
std::cerr << "Failed to listen!" << std::endl;
close(server_socket);
return -1;
}
// 等待客户端连接
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len);
if (client_socket == -1)
{
std::cerr << "Failed to accept client connection!" << std::endl;
close(server_socket);
return -1;
}
// 接收客户端请求信息
char buffer[1024];
int recv_len = recv(client_socket, buffer, sizeof(buffer), 0);
if (recv_len > 0)
{
buffer[recv_len] = '\0';
std::cout << "Received message: " << buffer << std::endl;
}
// 关闭套接字
close(client_socket);
close(server_socket);
return 0;
}
```
在该程序中,首先创建了一个TCP Socket,并绑定了地址和端口,然后监听该端口,等待客户端连接。当有客户端连接时,接受客户端请求信息,并将其打印出来。最后关闭客户端和服务端的套接字。
阅读全文