-
Notifications
You must be signed in to change notification settings - Fork 6
/
co_tcp_proxy.php
55 lines (50 loc) · 1.54 KB
/
co_tcp_proxy.php
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
<?php
class Co_TCP_ProxyServer
{
protected $backend_server = ['host' => '127.0.0.1', 'port' => 80];
protected $serv;
function run()
{
Co::set(['enable_reuse_port' => true]);
$serv = new Swoole\Server("127.0.0.1", 9509);
$serv->set(array(
'worker_num' => 4,
'max_coroutine' => 50000,
'log_level' => SWOOLE_LOG_WARNING,
));
$serv->on('Start', array($this, 'onStart'));
$serv->on('Receive', array($this, 'onReceive'));
$serv->start();
}
function onStart($serv)
{
$this->serv = $serv;
echo "Server: start.Swoole version is [" . SWOOLE_VERSION . "]\n";
}
function onReceive($serv, $fd, $tid, $data)
{
$socket = new Co\Client(SWOOLE_SOCK_TCP);
if ($socket->connect($this->backend_server['host'], $this->backend_server['port'], 2.0)) {
$socket->send($data);
$html = '';
while (true) {
$output = $socket->recv(8192 * 512);
if (!$output) {
break;
}
$html .= $output;
if (strlen($html) >= 10918) {
break;
}
}
$serv->send($fd, $html);
if (strstr($data, 'Connection: Keep-Alive') === false) {
$serv->close($fd);
}
} else {
echo "failed to connect the backend server, errno=" . $socket->errCode . "\n";
}
}
}
$serv = new Co_TCP_ProxyServer();
$serv->run();