-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
125 lines (110 loc) · 2.92 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include "requestData.h"
#include "epoll.h"
#include "threadpool.h"
#include "util.h"
#include <sys/epoll.h>
#include <queue>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <memory>
#define _PTHREADS 1
static const int MAXEVENTS = 5000;
static const int LISTENQ = 1024;
const int THREADPOOL_THREAD_NUM = 4;
const int QUEUE_SIZE = 65535;
const int PORT = 8888;
const int ASK_STATIC_FILE = 1;
const int ASK_IMAGE_STITCH = 2;
const int TIMER_TIME_OUT = 500;
void acceptConnection(int listen_fd, int epoll_fd, const std::string &path);
int socket_bind_listen(int port)
{
// 检查port值,取正确区间范围
if (port < 1024 || port > 65535)
return -1;
//创建 socket(IPv4 + TCP), 返回监听描述符
int listen_fd = 0;
if ((listen_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("creating socket failed \n");
return -1;
}
// 消除bind时"Address already in use"错误
int optval = 1;
if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1)
{
perror("重新綁定socket 與 端口失敗。\n");
return -1;
}
// 设置服务器IP和Port,和监听描述副绑定
struct sockaddr_in server_addr;
bzero((char *)&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons((unsigned short)port);
if (bind(listen_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
{
perror(" bind failed \r");
return -1;
}
if (listen(listen_fd, LISTENQ) == -1)
{
perror("listen failed \n");
return -1;
}
if (listen_fd == -1)
{
perror("bad listen_fd\n");
close(listen_fd);
return -1;
}
return listen_fd;
}
int main()
{
#ifndef _PTHREADS
printf("_PTHREADS is not defined! defined it 1.\n");
#endif
handle_for_sigpipe();
if (Epoll::epoll_init(MAXEVENTS, LISTENQ) < 0)
{
perror("epoll init failed");
return 1;
}
if (ThreadPool::threadpool_create(THREADPOOL_THREAD_NUM, QUEUE_SIZE) < 0)
{
printf("Threadpool create falied\n");
return 1;
}
int listen_fd = socket_bind_listen(PORT);
if (listen_fd < 0)
{
perror("socket bind failed");
return 1;
}
if (setSocketNonBlocking(listen_fd) < 0)
{
perror("set socket non block failed");
return 1;
}
std::shared_ptr<RequestData> request(new RequestData());
request->setFd(listen_fd);
if (Epoll::epoll_add(listen_fd, request, EPOLLIN | EPOLLET) < 0)
{
perror("epoll add error");
return 1;
}
while (true)
{
//sleep(10)
Epoll::my_epoll_wait(listen_fd, MAXEVENTS, -1);
}
return 0;
}