60 lines
1.7 KiB
C++

#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
const int BACKLOG = 5;
void listen(int port) {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
// 创建socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置服务器地址和端口号
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(port);
// 绑定socket到地址
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 开始监听客户端连接
if (listen(server_fd, BACKLOG) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
std::cout << "Server started, listening on port " << port << std::endl;
while(true) {
// 接受客户端连接请求并处理
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
std::cout << "New client connected: " << inet_ntoa(address.sin_addr) << ":" << ntohs(address.sin_port) << std::endl;
// 处理客户端请求
char buffer[1024] = {0};
int valread = read(new_socket , buffer, 1024);
std::cout << "Received message: " << buffer << std::endl;
const char* msg = "Hello from server!";
send(new_socket, msg, strlen(msg), 0);
// 关闭连接
close(new_socket);
}
}