前言
在实际的生产环境中,我们的服务程序往往需要同时监听多个端口,从bind系统调用的参数我们知道,一个socket只能与一个socket地址相绑定,即一个socket只能用来监听一个端口。因此要监听多个端口就需要创建多个socket,并将它们分别绑定多个端口,通过IO复用进行监听多个socket.
引入
通过刚才的介绍我们可以知道,即使是同一个端口,如果服务器要同时监听TCP和UDP请求,则也需要创建两个不同的socket:一个流socket,一个数据包socket,并将他们绑定到同一个端口上,添加到我们IO多路复用要监控的集合中。
代码实现
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <sys/epoll.h>
#include <iostream>
#define MAX_EVENT_NUMBER 1024
#define TCP_BUFFER_SIZE 512
#define UDP_BUFFER_SIZE 1024
int setnonblocking(int fd)
{
int old_flag = fcntl(fd,F_GETFL);
int new_f