在实际工作中,服务器需要同时监听和处理tcp和udp的套接字,同时监听N多的端口。根据bind系统调用来讲,一个socket只能监听一个端口,因此要创建多个socket并绑定到各个端口上。当然同一个端口可以同时绑定tcp和udp的socket,但是要创建两个socket,一个是tcp的一个是udp的。
下面我们就写一个可以同时处理tcp和udp服务的回射服务器。
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <pthread.h>
#define MAX_EVENT_NUMBER 1024
#define TCP_BUFFER_SIZE 512
#define UDP_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 )
{
epoll_event event;
event.data.fd = fd;