c++ epoll tcp udp high concurrent server code
Jump to turn (6)
- User
c++ epoll tcp udp high concurrent server code
- Assistant
c++ epoll tcp udp high concurrent server code
Creating a high-concurrent server using the C++ language incorporates multiple aspects, including TCP and UDP protocols, the epoll I/O event notification mechanism, and efficient handling of concurrent connections. Here is a basic example of the code for a high-concurrent server using epoll.
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <list>
#define MAX_EVENTS 1024
#define BUFFER_SIZE 1024
int setnonblocking(int fd) {
int old_option = fcntl(fd, F_GETFL);
int new_option = old_option | O_NONBLOCK;
fcntl(fd, F_SETFL, new_option);
return old_option;
}
void addfd(int epollfd, int fd, bool enable_et) {
epoll_event event;
event.data.fd = fd;
event.events = EPOLLIN;
if (enable_et) {
event.events |= EPOLLET;
}
epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event);
setnonblocking(fd);
}
int main(int argc, const char *argv[]) {
if (argc <= 2) {
std::cout << "Usage: " << argv[0] << " ip_address port_number" << std::endl;
return 1;
}
int port = atoi(argv[2]);
std::list<int> clients_list;
int ret = 0;
sockaddr_in address;
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
inet_pton(AF_INET, argv[1], &address.sin_addr);
address.sin_port = htons(port);
int listenfd = socket(PF_INET, SOCK_STREAM, 0);
if (listenfd == -1) {
std::cout << "Failed to create socket" << std::endl;
return -1;
}
ret = bind(listenfd, (sockaddr *)&address, sizeof(address));
if (ret == -1) {
std::cout << "Failed to bind socket" << std::endl;
return -1;
}
ret = listen(listenfd, 5);
if (ret == -1) {
std::cout << "Failed to listen socket" << std::endl;
return -1;
}
epoll_event events[MAX_EVENTS];
int epollfd = epoll_create(5);
if (epollfd == -1) {
std::cout << "Failed to create epoll fd" << std::endl;
return -1;
}
addfd(epollfd, listenfd, true);
while (true) {
int event_count = epoll_wait(epollfd, events, MAX_EVENTS, -1);
if (event_count < 0) {
std::cout << "epoll_wait failure" << std::endl;
break;
}
for (int i = 0; i < event_count; i++) {
int sockfd = events[i].data.fd;
if (sockfd == listenfd) {
sockaddr_in client_address;
socklen_t client_addrlength = sizeof(client_address);
int connfd = accept(listenfd, (sockaddr *)&client_address, &client_addrlength);
addfd(epollfd, connfd, true);
clients_list.push_back(connfd);
std::cout << "New client connected" << std::endl;
} else if (events[i].events & EPOLLIN) {
char buffer[BUFFER_SIZE];
memset(buffer, '\0', BUFFER_SIZE);
int data_read = recv(sockfd, buffer, BUFFER_SIZE, 0);
if (data_read < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
std::cout << "Read later" << std::endl;
continue;
}
close(sockfd);
clients_list.remove(sockfd);
std::cout << "A client left" << std::endl;
} else if (data_read == 0) {
close(sockfd);
clients_list.remove(sockfd);
std::cout << "A client left" << std::endl;
} else {
// Handle the data
std::cout << "Received data: " << buffer << std::endl;
// Send the same data back to the client
send(sockfd, buffer, data_read, 0);
}
} else {
std::cout << "Unhandled epoll event" << std::endl;
}
}
}
close(listenfd); // Close the socket
return 0;
}
This example is a basic high-concurrent server using epoll to handle multiple client connections simultaneously. You can build upon this and add additional features like TCP, UDP, or extend it as needed.
c++ epollet tcp udp high concurrent server code
Implementing a high-concurrent server with edge-triggered (ET) epoll for both TCP and UDP connections requires handling TCP and UDP sockets separately in the server logic. Here's an example of both TCP and UDP ET-based epoll server code:
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <list>
#define MAX_EVENTS 1024
#define BUFFER_SIZE 1024
int setnonblocking(int fd) {
int old_option = fcntl(fd, F_GETFL);
int new_option = old_option | O_NONBLOCK;
fcntl(fd, F_SETFL, new_option);
return old_option;
}
void addfd(int epollfd, int fd, bool enable_et) {
epoll_event event;
event.data.fd = fd;
event.events = EPOLLIN;
if (enable_et) {
event.events |= EPOLLET;
}
epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event);
setnonblocking(fd);
}
int main(int argc, const char *argv[]) {
if (argc <= 2) {
std::cout << "Usage: " << argv[0] << " ip_address port_number" << std::endl;
return 1;
}
int port = atoi(argv[2]);
std::list<int> clients_list;
int ret = 0;
sockaddr_in address;
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
inet_pton(AF_INET, argv[1], &address.sin_addr);
address.sin_port = htons(port);
c++ epollet tcp udp client code
To demonstrate how to create an ET-based epoll TCP and UDP client, you'll need to construct a client that sends messages to the server accordingly. Here's a client code example for both TCP and UDP connections:
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#define MAX_EVENTS 10
#define BUFFER_SIZE 1024
int setnonblocking(int fd) {
int old_option = fcntl(fd, F_GETFL);
int new_option = old_option | O_NONBLOCK;
fcntl(fd, F_SETFL, new_option);
return old_option;
}
void addfd(int epollfd, int fd, bool enable_et) {
epoll_event event;
event.data.fd = fd;
event.events = EPOLLIN;
if (enable_et) {
event.events |= EPOLLET;
}
epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event);
setnonblocking(fd);
}
int main(int argc, const char *argv[]) {
if (argc <= 2) {
std::cout << "Usage: " << argv[0] << " ip_address port_number" << std::endl;
return 1;
}
int port = atoi(argv[2]);
int ret = 0;
sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
inet_pton(AF_INET, argv[1], &server_address.sin_addr);
server_address.sin_port = htons(port);
c++ epollet tcp udp ipv4 ipv6 client code
Here's an example of an edge-triggered epoll-based client for both TCP and UDP, supporting IPv4 and IPv6:
c++ socket sendmsg recvmsg for tcp and udp
To create a C++ example that demonstrates how to use sendmsg and recvmsg for both TCP and UDP connections, follow these steps:
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
int main(int argc, const char *argv[]) {
if (argc <= 2) {
std::cout << "Usage: " << argv[0] << " ip_address port_number" << std::endl;
return 1;
}
const char* ip = argv[1];
const char* port = argv[2];
addrinfo hints, *res;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // Unspecified, can be either IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM;
int status = getaddrinfo(ip, port, &hints, &res);
if (status != 0) {
std::cout << "getaddrinfo error: " << gai_strerror(status) << std::endl;
return 1;
}
int tcp_sockfd = socket(res->ai_family, res->ai_socktype, 0);
if (tcp_sockfd == -1) {
std::cout << "Failed to create TCP socket" << std::endl;
freeaddrinfo(res);
return -1;
}
int udp_sockfd = socket(res->ai_family, SOCK_DGRAM, 0);
if (udp_sockfd == -1) {
std::cout << "Failed to create UDP socket" << std::endl;
freeaddrinfo(res);
return -1;
}
c/c++ how to convert struct addrinfo to struct sockaddr_storage
Converting a struct addrinfo to a struct sockaddr_storage is straightforward because this conversion actually involves copying the sockaddr structure embedded within the addrinfo structure into the sockaddr_storage structure. The sockaddr_storage structure is large enough to contain both IPv4 and IPv6 addresses, so you don't need to worry about the underlying address type when performing the conversion.
Here's a simple example of how to create a function that converts a struct addrinfo to a struct sockaddr_storage:
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
void addrinfo_to_sockaddr_storage(struct addrinfo *input, struct sockaddr_storage *output) {
if (input->ai_family == AF_INET) {
memcpy(output, input->ai_addr, sizeof(struct sockaddr_in));
} else if (input->ai_family == AF_INET6) {
memcpy(output, input->ai_addr, sizeof(struct sockaddr_in6));
} else {
std::cout << "Unknown address family" << std::endl;
}
}
int main() {
const char* ip = "127.0.0.1";
const char* port = "80";
addrinfo hints, *res;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
int status = getaddrinfo(ip, port, &hints, &res);
if (status != 0) {
std::cout << "getaddrinfo error: " << gai_strerror(status) << std::endl;
return 1;
}
sockaddr_storage converted_address;
addrinfo_to_sockaddr_storage(res, &converted_address);
// The converted_address now contains the IP address and port from res->ai_addr
// You can use the sockaddr_storage struct as needed
freeaddrinfo(res);
return 0;
}
In this example, the addrinfo_to_sockaddr_storage function converts an addrinfo structure to a sockaddr_storage structure by copying the appropriate data from ai_addr within the addrinfo input structure. The main function demonstrates how to use this function to convert the address from a getaddrinfo result.
Make sure to include the necessary headers when using these structures and functions in your code.
Not yet included in a published release.
int tcp_listenfd = socket(PF_INET, SOCK_STREAM, 0);
if (tcp_listenfd == -1) {
std::cout << "Failed to create TCP socket" << std::endl;
return -1;
}
int udp_sockfd = socket(PF_INET, SOCK_DGRAM, 0);
if (udp_sockfd == -1) {
std::cout << "Failed to create UDP socket" << std::endl;
return -1;
}
ret = bind(tcp_listenfd, (sockaddr *)&address, sizeof(address));
if (ret == -1) {
std::cout << "Failed to bind TCP socket" << std::endl;
return -1;
}
ret = listen(tcp_listenfd, 5);
if (ret == -1) {
std::cout << "Failed to listen to TCP socket" << std::endl;
return -1;
}
ret = bind(udp_sockfd, (sockaddr *)&address, sizeof(address));
if (ret == -1) {
std::cout << "Failed to bind UDP socket" << std::endl;
return -1;
}
epoll_event events[MAX_EVENTS];
int epollfd = epoll_create(5);
if (epollfd == -1) {
std::cout << "Failed to create epoll fd" << std::endl;
return -1;
}
addfd(epollfd, tcp_listenfd, true);
addfd(epollfd, udp_sockfd, true);
while (true) {
int event_count = epoll_wait(epollfd, events, MAX_EVENTS, -1);
if (event_count < 0) {
std::cout << "epoll_wait failure" << std::endl;
break;
}
for (int i = 0; i < event_count; i++) {
int sockfd = events[i].data.fd;
if (sockfd == tcp_listenfd) {
sockaddr_in client_address;
socklen_t client_addrlength = sizeof(client_address);
int connfd = accept(tcp_listenfd, (sockaddr *)&client_address, &client_addrlength);
addfd(epollfd, connfd, true);
clients_list.push_back(connfd);
std::cout << "New TCP client connected" << std::endl;
} else if (sockfd == udp_sockfd) {
sockaddr_in client_address;
socklen_t client_addrlength = sizeof(client_address);
char buffer[BUFFER_SIZE];
memset(buffer, '\0', BUFFER_SIZE);
int data_read = recvfrom(udp_sockfd, buffer, BUFFER_SIZE, 0,
(sockaddr *)&client_address, &client_addrlength);
if (data_read <= 0) {
continue;
}
// Handle the data
std::cout << "Received UDP data: " << buffer << std::endl;
// Send the same data back to the client
sendto(udp_sockfd, buffer, data_read, 0,
(sockaddr *)&client_address, client_addrlength);
} else if (events[i].events & EPOLLIN) {
char buffer[BUFFER_SIZE];
memset(buffer, '\0', BUFFER_SIZE);
int data_read = recv(sockfd, buffer, BUFFER_SIZE, 0);
if (data_read < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
std::cout << "Read later" << std::endl;
continue;
}
close(sockfd);
clients_list.remove(sockfd);
std::cout << "A TCP client left" << std::endl;
} else if (data_read == 0) {
close(sockfd);
clients_list.remove(sockfd);
std::cout << "A TCP client left" << std::endl;
} else {
// Handle the data
std::cout << "Received TCP data: " << buffer << std::endl;
// Send the same data back to the client
send(sockfd, buffer, data_read, 0);
}
} else {
std::cout << "Unhandled epoll event" << std::endl;
}
}
}
close(tcp_listenfd); // Close the TCP socket
close(udp_sockfd); // Close the UDP socket
return 0;
}
This example demonstrates how to create a high-concurrent server using edge-triggered epoll for both TCP and UDP connections.
int tcp_sockfd = socket(PF_INET, SOCK_STREAM, 0);
if (tcp_sockfd == -1) {
std::cout << "Failed to create TCP socket" << std::endl;
return -1;
}
int udp_sockfd = socket(PF_INET, SOCK_DGRAM, 0);
if (udp_sockfd == -1) {
std::cout << "Failed to create UDP socket" << std::endl;
return -1;
}
ret = connect(tcp_sockfd, (sockaddr *)&server_address, sizeof(server_address));
if (ret == -1) {
std::cout << "Failed to connect to server" << std::endl;
return -1;
}
epoll_event events[MAX_EVENTS];
int epollfd = epoll_create(2);
if (epollfd == -1) {
std::cout << "Failed to create epoll fd" << std::endl;
return -1;
}
addfd(epollfd, tcp_sockfd, true);
addfd(epollfd, udp_sockfd, true);
while (true) {
std::cout << "Enter a message to send to the server (TCP): ";
std::string tcp_msg;
std::getline(std::cin, tcp_msg);
send(tcp_sockfd, tcp_msg.c_str(), tcp_msg.size(), 0);
std::cout << "Enter a message to send to the server (UDP): ";
std::string udp_msg;
std::getline(std::cin, udp_msg);
sendto(udp_sockfd, udp_msg.c_str(), udp_msg.size(), 0,
(sockaddr *)&server_address, sizeof(server_address));
int event_count = epoll_wait(epollfd, events, MAX_EVENTS, -1);
if (event_count < 0) {
std::cout << "epoll_wait failure" << std::endl;
break;
}
for (int i = 0; i < event_count; i++) {
int sockfd = events[i].data.fd;
if (sockfd == tcp_sockfd || sockfd == udp_sockfd) {
char buffer[BUFFER_SIZE];
memset(buffer, '\0', BUFFER_SIZE);
int data_read = recv(sockfd, buffer, BUFFER_SIZE, 0);
if (data_read < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
std::cout << "Read later" << std::endl;
continue;
}
close(sockfd);
std::cout << "Disconnected" << std::endl;
} else if (data_read == 0) {
close(sockfd);
std::cout << "Disconnected" << std::endl;
} else {
std::cout << "Received: " << buffer << std::endl;
}
} else {
std::cout << "Unhandled epoll event" << std::endl;
}
}
}
close(tcp_sockfd); // Close the TCP socket
close(udp_sockfd); // Close the UDP socket
return 0;
}
The example above shows how to create an Epoll-ET (edge-triggered) based TCP and UDP client that can send and receive messages from a server supporting TCP and UDP connections. It waits for the user to enter messages that the client will send through TCP and UDP to the server, and it displays the response received from the server.
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <netdb.h>
#define MAX_EVENTS 10
#define BUFFER_SIZE 1024
int setnonblocking(int fd) {
int old_option = fcntl(fd, F_GETFL);
int new_option = old_option | O_NONBLOCK;
fcntl(fd, F_SETFL, new_option);
return old_option;
}
void addfd(int epollfd, int fd, bool enable_et) {
epoll_event event;
event.data.fd = fd;
event.events = EPOLLIN;
if (enable_et) {
event.events |= EPOLLET;
}
epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event);
setnonblocking(fd);
}
int main(int argc, const char *argv[]) {
if (argc < 4) {
std::cout << "Usage: " << argv[0] << " ip_address port_number protocol(IPv4/IPv6)" << std::endl;
return 1;
}
const char* ip = argv[1];
const char* port = argv[2];
const char* ip_version = argv[3];
int protocol = 0;
if (strcmp(ip_version, "IPv6") == 0) {
protocol = AF_INET6;
} else if (strcmp(ip_version, "IPv4") == 0) {
protocol = AF_INET;
} else {
std::cout << "Invalid IP version input. Use 'IPv4' or 'IPv6'" << std::endl;
return 1;
}
addrinfo hints, *res;
memset(&hints, 0, sizeof(hints));
hints.ai_family = protocol;
hints.ai_socktype = SOCK_STREAM;
int status = getaddrinfo(ip, port, &hints, &res);
if (status != 0) {
std::cout << "getaddrinfo error: " << gai_strerror(status) << std::endl;
return 1;
}
int tcp_sockfd = socket(res->ai_family, res->ai_socktype, 0);
if (tcp_sockfd == -1) {
std::cout << "Failed to create TCP socket" << std::endl;
freeaddrinfo(res);
return -1;
}
int udp_sockfd = socket(res->ai_family, SOCK_DGRAM, 0);
if (udp_sockfd == -1) {
std::cout << "Failed to create UDP socket" << std::endl;
freeaddrinfo(res);
return -1;
}
if (connect(tcp_sockfd, res->ai_addr, res->ai_addrlen) == -1) {
std::cout << "Failed to connect to server" << std::endl;
close(tcp_sockfd);
close(udp_sockfd);
freeaddrinfo(res);
return -1;
}
epoll_event events[MAX_EVENTS];
int epollfd = epoll_create1(0);
if (epollfd == -1) {
std::cout << "Failed to create epoll fd" << std::endl;
close(tcp_sockfd);
close(udp_sockfd);
freeaddrinfo(res);
return -1;
}
addfd(epollfd, tcp_sockfd, true);
addfd(epollfd, udp_sockfd, true);
freeaddrinfo(res);
while (true) {
std::cout << "Enter a message to send to the server (TCP): ";
std::string tcp_msg;
std::getline(std::cin, tcp_msg);
send(tcp_sockfd, tcp_msg.c_str(), tcp_msg.size(), 0);
std::cout << "Enter a message to send to the server (UDP): ";
std::string udp_msg;
std::getline(std::cin, udp_msg);
sendto(udp_sockfd, udp_msg.c_str(), udp_msg.size(), 0,
res->ai_addr, res->ai_addrlen);
int event_count = epoll_wait(epollfd, events, MAX_EVENTS, -1);
if (event_count < 0) {
std::cout << "epoll_wait failure" << std::endl;
break;
}
for (int i = 0; i < event_count; i++) {
int sockfd = events[i].data.fd;
if (sockfd == tcp_sockfd || sockfd == udp_sockfd) {
char buffer[BUFFER_SIZE];
memset(buffer, '\0', BUFFER_SIZE);
int data_read = recv(sockfd, buffer, BUFFER_SIZE, 0);
if (data_read < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
std::cout << "Read later" << std::endl;
continue;
}
close(sockfd);
std::cout << "Disconnected" << std::endl;
} else if (data_read == 0) {
close(sockfd);
std::cout << "Disconnected" << std::endl;
} else {
std::cout << "Received: " << buffer << std::endl;
}
} else {
std::cout << "Unhandled epoll event" << std::endl;
}
}
}
close(tcp_sockfd); // Close the TCP socket
close(udp_sockfd); // Close the UDP socket
return 0;
}
This client code supports connections to both IPv4 and IPv6 servers using TCP and UDP protocols. You can specify the IP version as a command line argument when running the client.
if (connect(tcp_sockfd, res->ai_addr, res->ai_addrlen) == -1) {
std::cout << "Failed to connect to server" << std::endl;
close(tcp_sockfd);
close(udp_sockfd);
freeaddrinfo(res);
return -1;
}
while (true) {
std::cout << "Enter a message to send to the server (TCP): ";
std::string tcp_msg;
std::getline(std::cin, tcp_msg);
struct iovec iov_tcp;
iov_tcp.iov_base = &tcp_msg[0]; // Pointer to data
iov_tcp.iov_len = tcp_msg.size(); // Length of data
msghdr msg_tcp;
memset(&msg_tcp, 0, sizeof(msg_tcp));
msg_tcp.msg_iov = &iov_tcp;
msg_tcp.msg_iovlen = 1;
sendmsg(tcp_sockfd, &msg_tcp, 0);
std::cout << "Enter a message to send to the server (UDP): ";
std::string udp_msg;
std::getline(std::cin, udp_msg);
struct iovec iov_udp;
iov_udp.iov_base = &udp_msg[0]; // Pointer to data
iov_udp.iov_len = udp_msg.size(); // Length of data
msghdr msg_udp;
memset(&msg_udp, 0, sizeof(msg_udp));
msg_udp.msg_name = res->ai_addr;
msg_udp.msg_namelen = res->ai_addrlen;
msg_udp.msg_iov = &iov_udp;
msg_udp.msg_iovlen = 1;
sendmsg(udp_sockfd, &msg_udp, 0);
char tcp_buffer[1024];
struct iovec iov_tcp_recv;
iov_tcp_recv.iov_base = tcp_buffer;
iov_tcp_recv.iov_len = sizeof(tcp_buffer);
msghdr msg_tcp_recv;
memset(&msg_tcp_recv, 0, sizeof(msg_tcp_recv));
msg_tcp_recv.msg_iov = &iov_tcp_recv;
msg_tcp_recv.msg_iovlen = 1;
int bytes_received_tcp = recvmsg(tcp_sockfd, &msg_tcp_recv, 0);
if (bytes_received_tcp > 0) {
tcp_buffer[bytes_received_tcp] = '\0';
std::cout << "TCP Received: " << tcp_buffer << std::endl;
}
char udp_buffer[1024];
struct iovec iov_udp_recv;
iov_udp_recv.iov_base = udp_buffer;
iov_udp_recv.iov_len = sizeof(udp_buffer);
sockaddr_storage recv_addr;
socklen_t recv_addr_len = sizeof(recv_addr);
msghdr msg_udp_recv;
memset(&msg_udp_recv, 0, sizeof(msg_udp_recv));
msg_udp_recv.msg_name = &recv_addr;
msg_udp_recv.msg_namelen = recv_addr_len;
msg_udp_recv.msg_iov = &iov_udp_recv;
msg_udp_recv.msg_iovlen = 1;
int bytes_received_udp = recvmsg(udp_sockfd, &msg_udp_recv, 0);
if (bytes_received_udp > 0) {
udp_buffer[bytes_received_udp] = '\0';
std::cout << "UDP Received: " << udp_buffer << std::endl;
}
}
close(tcp_sockfd);
close(udp_sockfd);
freeaddrinfo(res);
return 0;
}
This example demonstrates how to create a C++ client that connects to a server using TCP and also sends messages with UDP. The client uses the sendmsg and recvmsg functions to send and receive messages using both TCP and UDP protocols. The client runs in an infinite loop and allows you to send messages to the server and receive messages from the server until you terminate the program.