-
Notifications
You must be signed in to change notification settings - Fork 27
/
HttpServer.cs
265 lines (237 loc) · 9.58 KB
/
HttpServer.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
namespace ja_learner
{
internal class HttpServer
{
private static string _rootFolder = Directory.GetCurrentDirectory() + @"\dist";
private static HttpListener _httpListener;
private static IWebProxy direct, proxy;
public static void StartServer()
{
port = FindAvailablePort();
_httpListener = new HttpListener();
_httpListener.Prefixes.Add($"http://localhost:{port}/"); // 服务器监听的URL和端口号
proxyDict["/mojiapi"] = "https://api.mojidict.com";
proxyDict["/googletrans_api"] = "https://translate.googleapis.com";
proxyDict["/googletrans"] = "https://translate.googleapis.com/translate_a";
proxyDict["/ankiconnect"] = Program.APP_SETTING.Anki.AnkiConnectUrl;
direct = HttpClient.DefaultProxy;
if(Program.APP_SETTING.HttpProxy != string.Empty)
{
proxy = new WebProxy(Program.APP_SETTING.HttpProxy);
}
else
{
proxy = direct;
}
Task.Run(() =>
{
try
{
_httpListener.Start();
while (_httpListener.IsListening)
{
var context = _httpListener.GetContext();
Task.Run(() => HandleRequest(context));
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
});
}
private static int port;
public static int Port
{
get { return port; }
}
static int FindAvailablePort()
{
int port = Program.APP_SETTING.Port;
while (IsPortInUse(port) && port < 65536)
{
port++;
}
return port;
}
static bool IsPortInUse(int port)
{
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] activeTcpListeners = properties.GetActiveTcpListeners();
IPEndPoint[] activeUdpListeners = properties.GetActiveUdpListeners();
foreach (IPEndPoint endPoint in activeTcpListeners)
{
if (endPoint.Port == port)
{
return true;
}
}
foreach (IPEndPoint endPoint in activeUdpListeners)
{
if (endPoint.Port == port)
{
return true;
}
}
return false;
}
// private static string googleServer = "translate.googleapis.com";
private static Dictionary<string, string> proxyDict = new Dictionary<string, string>();
private static async void HandleRequest(HttpListenerContext context)
{
var request = context.Request;
var response = context.Response;
// 获取请求的文件路径
var localPath = request.Url.LocalPath.TrimStart('/');
var filePath = string.IsNullOrEmpty(localPath) ? Path.Combine(_rootFolder, "index.html") : Path.Combine(_rootFolder, localPath);
string url = request.Url.LocalPath;
string proxyName = proxyDict.Keys.FirstOrDefault(key => url.StartsWith(key));
// 代理
if (proxyName != null)
{
HttpClient.DefaultProxy = UserConfig.UseProxy ? proxy : direct;
try
{
using (HttpClient httpClient = new HttpClient())
{
HttpResponseMessage r;
string apiUrl = request.Url.PathAndQuery.Replace(proxyName, proxyDict[proxyName]);
if (request.HttpMethod == "GET")
{
r = await httpClient.GetAsync(request.RawUrl.Replace(proxyName, proxyDict[proxyName]));
}
else
{
string json = "";
using (StreamReader reader = new StreamReader(request.InputStream))
{
json = reader.ReadToEnd();
}
httpClient.DefaultRequestHeaders.Clear();
// httpClient.DefaultRequestHeaders.Host = proxyDict[proxyName].Replace("https://", "");
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
content.Headers.Clear();
// 将HttpListenerRequest的头信息复制到HttpContent的头信息
foreach (string headerName in request.Headers.AllKeys)
{
// 根据需要自定义头信息的处理
string headerValue = request.Headers[headerName];
if (!string.IsNullOrEmpty(headerValue))
{
content.Headers.TryAddWithoutValidation(headerName, headerValue);
}
}
r = await httpClient.PostAsync(apiUrl, content);
}
// 将代理请求的响应返回给客户端
response.StatusCode = (int)r.StatusCode;
response.ContentType = r.Content.Headers.ContentType?.ToString();
byte[] buffer = await r.Content.ReadAsByteArrayAsync();
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
}
response.Close();
}catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else if (File.Exists(filePath))
{
try
{
// 发送文件内容作为响应
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
response.ContentLength64 = fs.Length;
response.ContentType = GetMimeType(filePath);
fs.CopyTo(response.OutputStream);
}
}
catch (Exception ex)
{
response.StatusCode = (int)HttpStatusCode.InternalServerError;
response.Close();
return;
}
response.StatusCode = (int)HttpStatusCode.OK;
response.Close();
}
else
{
// 请求为路由
var vueIndexPath = Path.Combine(_rootFolder, "index.html");
if (File.Exists(vueIndexPath))
{
try
{
// 读取Vue应用的入口点文件
var vueIndexContent = File.ReadAllText(vueIndexPath);
// 设置响应的Content-Type
response.ContentType = "text/html";
// 发送Vue应用的入口点文件内容作为响应
var buffer = Encoding.UTF8.GetBytes(vueIndexContent);
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
}
catch (Exception ex)
{
response.StatusCode = (int)HttpStatusCode.InternalServerError;
response.Close();
return;
}
response.StatusCode = (int)HttpStatusCode.OK;
response.Close();
}
else
{
response.StatusCode = (int)HttpStatusCode.NotFound;
response.Close();
}
}
}
private static string GetMimeType(string filePath)
{
// 根据文件扩展名获取相应的MIME类型
string mimeType;
var extension = Path.GetExtension(filePath).ToLower();
switch (extension)
{
case ".html":
mimeType = "text/html";
break;
case ".css":
mimeType = "text/css";
break;
case ".js":
mimeType = "application/javascript";
break;
case ".png":
mimeType = "image/png";
break;
case ".jpg":
case ".jpeg":
mimeType = "image/jpeg";
break;
case ".gif":
mimeType = "image/gif";
break;
case ".svg":
mimeType = "image/svg+xml";
break;
default:
mimeType = "application/octet-stream";
break;
}
return mimeType;
}
}
}