-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.php
More file actions
375 lines (294 loc) · 9.04 KB
/
http.php
File metadata and controls
375 lines (294 loc) · 9.04 KB
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
<?php
class Http
{
/**
* 存放select类的初始化
*/
public static $globalEvent;
/**
* 协议转换数组
*/
protected $builtinTransports = array(
'tcp' => 'tcp',
'udp' => 'udp',
'unix' => 'unix',
'ssl' => 'tcp',
);
/**
* 默认协议
*/
protected $transport = "tcp";
/**
* 协议命名空间字符串
*/
protected $protocol;
/**
* 流服务内容
*/
protected $context;
/**
* 主socket
*/
protected $mainSocket;
const EV_READ = 1;
/**
* worker id
*/
protected $workerId;
/**
* 所有woeker的集合数组
*/
protected static $workers = array();
/**
* socket名称
*/
protected $socketName;
protected $pauseAccept = true;
/**
* 构造函数
*/
public function __construct($socket_name = "", array $context_option = array())
{
$this->workerId = \spl_object_hash($this);
static::$workers[$this->workerId] = $this;
if ($socket_name) {
$this->socketName = $socket_name;
if (!isset($context_option['socket']['backlog'])) {
$context_option['socket']['backlog'] = 102400;
}
$this->context = stream_context_create($context_option);
}
}
/**
* 执行函数
*/
public static function runAll()
{
reset(static::$workers);
$worker = current(static::$workers);
static::$globalEvent = new select();
$worker->listen();
\restore_error_handler();
static::$globalEvent->loop();
}
public function acceptConnection($socket)
{
set_error_handler(function(){});
$new_socket = stream_socket_accept($socket, 0, $remote_address);
restore_error_handler();
if (!$new_socket) {
return;
}
new TcpConnection($new_socket,$remote_address);
}
/**
* 监听
*/
protected function listen()
{
if(!$this->socketName)
{
return ;
}
if (!$this->mainSocket) {
$local_socket = $this->paserSchemeAddress();
$flags = $this->transport === 'udp' ? \STREAM_SERVER_BIND : \STREAM_SERVER_BIND | \STREAM_SERVER_LISTEN;
$errno = 0;
$errmsg = '';
stream_context_set_option($this->context, 'socket', 'so_reuseport', 1);
$this->mainSocket = stream_socket_server($local_socket,$errno,$errmsg,$flags,$this->context);
if(!$this->mainSocket)
{
throw new Exception($errmsg);
}
//而这里把stream转换成了sokect类型了
if(function_exists('socket_import_stream') && $this->builtinTransports[$this->transport] === 'tcp')
{
set_error_handler(function(){});
$socket = socket_import_stream($this->mainSocket);
socket_set_option($socket,SOL_SOCKET,SO_KEEPALIVE,1);
socket_set_option($socket,SOL_TCP,TCP_NODELAY,1);
restore_error_handler();
}
//设置不阻塞模式
stream_set_blocking($this->mainSocket,false);
}
$this->accept();
}
protected function accept()
{
if (static::$globalEvent && true === $this->pauseAccept && $this->mainSocket) {
if ($this->transport !== 'udp') {
static::$globalEvent->add($this->mainSocket, self::EV_READ, array($this, 'acceptConnection'));
}
$this->pauseAccept = false;
}
}
/**
* 解析协议头
*/
protected function paserSchemeAddress()
{
if (!$this->socketName) {
return;
}
list($scheme, $address) = \explode(':', $this->socketName, 2);
if(!isset($this->builtinTransports[$scheme]))
{
//就用协议解析类命名空间
$this->protocol = 'http';
}
else
{
$this->transport = $scheme;
}
return $this->builtinTransports[$this->transport].':'.$address;
}
}
class Select
{
protected $allEvents = [];
protected $readFds = array();
protected $exceptFds = array();
protected $writeFds = array();
protected $selectTimeOut = 100000000;
protected $_scheduler = null;
const EV_READ = 1;
/**
* Construct.
*/
public function __construct()
{
// Init SplPriorityQueue.
$this->_scheduler = new \SplPriorityQueue();
$this->_scheduler->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
}
/**
* 添加
*/
public function add($fd,$flag,$func,$args = array())
{
$fd_key = (int)$fd;
$this->allEvents[$fd_key][$flag] = array($func, $fd);
$this->readFds[$fd_key] = $fd;
return true;
}
public function loop()
{
while (1) {
$read = $this->readFds;
$write = $this->writeFds;
$except = $this->exceptFds;
$ret = false;
if($read || $write || $except)
{
try {
$ret = @stream_select($read, $write, $except, 0, $this->selectTimeOut);
} catch (\Exception $e) {} catch (\Error $e) {}
}
else
{
$this->selectTimeOut >= 1 && usleep((int)$this->selectTimeOut);
$ret = false;
}
if (!$ret) {
continue;
}
if ($read) {
foreach ($read as $fd) {
$fd_key = (int)$fd;
if (isset($this->allEvents[$fd_key][self::EV_READ])) {
\call_user_func_array($this->allEvents[$fd_key][self::EV_READ][0],
array($this->allEvents[$fd_key][self::EV_READ][1]));
}
}
}
}
}
}
class TcpConnection
{
protected $socket;
const EV_READ = 1;
protected $bytesRead;
protected $recvBuffer;
protected $isPaused = false;
/**
* 当前数据包的长度
*/
protected $currentPackageLength;
/**
* 最大数据包的大小
*/
protected $maxPackageSize = 1048576;
public function __construct($socket, $remote_address = '')
{
$this->socket = $socket;
stream_set_blocking($this->socket, 0);
stream_set_read_buffer($this->socket, 0);
Http::$globalEvent->add($this->socket,self::EV_READ,array($this, 'baseRead'));
}
public function baseRead($socket, $check_eof = true)
{
echo "baseRead";
$buffer = '';
try {
$buffer = @fread($socket, 65535);
} catch (\Exception $e) {} catch (\Error $e) {}
if ($buffer === '' || $buffer === false) {
if ($check_eof && (feof($socket) || !is_resource($socket) || $buffer === false)) {
}
}else
{
$this->bytesRead += strlen($buffer);
$this->recvBuffer .= $buffer;
}
while ($this->recvBuffer !== '' && !$this->isPaused)
{
if ($this->currentPackageLength)
{
if ($this->currentPackageLength > strlen($this->recvBuffer))
{
break;
}
}
$crlf_pos = strpos($this->recvBuffer, "\r\n\r\n");
$head_len = $crlf_pos + 4;
$method = strstr($this->recvBuffer, ' ', true);
if ($method === 'GET')
{
$this->currentPackageLength = $head_len;
}
if ($this->currentPackageLength === 0) {
break;
}
elseif ($this->currentPackageLength > 0 && $this->currentPackageLength <= $this->maxPackageSize)
{
if ($this->currentPackageLength > strlen($this->recvBuffer))
{
break;
}
}
if (strlen($this->recvBuffer) === $this->currentPackageLength)
{
$one_request_buffer = $this->recvBuffer;
$this->recvBuffer = '';
}
$this->currentPackageLength = 0;
//然后解析$one_request_buffer 数据包,代码就忽略了具体可以看HTTP协议里面Request类
//后面就调用onMessage 自定义函数 这里做个忽略了...
$this->send("12333333");
}
}
public function send($send_buffer)
{
$ext_header = '';
$body_len = strlen($send_buffer);
$send = "HTTP/1.1 200 OK\r\nServer: xiaobo\r\n{$ext_header}Connection: keep-alive\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length: $body_len\r\n\r\n$send_buffer";
$len = 0;
$len = @fwrite($this->socket, $send);
fclose($this->socket);
}
}
$http = new Http("http://0.0.0.0:8053");
Http::runAll();