proxyImapServer.php
3.3 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
<?php
require_once "Auth.php";
require_once "ImapClientSwoole.php";
class ProxyService
{
/**
* 连接数
* @var ImapClient[]
*/
protected static $clients = [];
/**
* @author:dc
* @time 2025/3/29 14:34
*/
public function run()
{
//创建Server对象,监听 127.0.0.1:9501 端口。
$server = new Swoole\Server('0.0.0.0', 9527, SWOOLE_PROCESS, SWOOLE_SOCK_TCP);
//监听连接进入事件。
$server->on('Connect', function ($server, $fd) {});
//监听数据接收事件。
$server->on('Receive', function ($server, $fd, $reactor_id, $data) {
// 建立连接
if (empty(self::$clients[$fd])) {
try {
$auth = new Auth($data);
}catch (Throwable $e){
$server->send($fd, $e->getMessage());
$server->close($fd,true);
return;
}
// 创建一个客户端
self::$clients[$fd] = new ImapClientSwoole($auth->host);
// 连接客户端
try {
self::$clients[$fd]->open($auth->out_ip, $auth->timeOut);
}catch (Throwable $e){
$server->send($fd, $auth->tag . ' BAD ' . $e->getMessage()."\r\n");
$server->close($fd,true);
return;
}
// 发送成功消息
$server->send($fd, $auth->tag . " OK The proxy server is successfully connected.\r\n");
// 读取数据
while (1){
if (empty(self::$clients[$fd])){
break;
}
$line = self::$clients[$fd]->readLine();
if($line){
echo '读取到 => '.$line;
$server->send($fd,$line);
}else{
co::sleep(0.1);
}
}
} // 正式请求转发
else {
// 没有连接成功
if(empty(self::$clients[$fd])){
$server->send($fd, " No proxy server.\r\n");
$server->close($fd,true);
return;
}
// 请求数据
$writeNumber = self::$clients[$fd]->write($data);
list($tag,$cmd) = explode(' ',$data,2);
// 退出命令就不等待服务器了
if(trim($cmd) == 'LOGOUT'){
$server->send($fd, $tag." OK bye.\r\n");
$server->close($fd,true);
return;
}
if($writeNumber){
echo '成功写入 => '.$data;
}else{
echo '写入失败 => '.$data;
$server->send($fd,$tag.' BAD '.$writeNumber."\r\n");
}
}
});
//监听连接关闭事件。
$server->on('Close', function ($server, $fd) {
echo '连接关闭了 => '.$fd."\n";
// 关闭并释放资源
self::$clients[$fd] = null;
unset(self::$clients[$fd]);
});
//启动服务器
$server->start();
}
}
(new ProxyService())->run();