Create main.py
Browse files
main.py
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, Request, WebSocket
|
2 |
+
from fastapi.responses import StreamingResponse
|
3 |
+
import httpx
|
4 |
+
import websockets
|
5 |
+
import asyncio
|
6 |
+
|
7 |
+
# 定义反向代理的端口
|
8 |
+
PROXY_PORT = 7860
|
9 |
+
# 定义目标服务器的端口
|
10 |
+
TARGET_PORT = 33495
|
11 |
+
|
12 |
+
app = FastAPI()
|
13 |
+
|
14 |
+
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH"])
|
15 |
+
async def http_proxy(request: Request, path: str):
|
16 |
+
# 构建目标URL
|
17 |
+
target_url = f"http://localhost:{TARGET_PORT}/{path}"
|
18 |
+
url_params = dict(request.query_params)
|
19 |
+
|
20 |
+
# 创建一个异步HTTP客户端
|
21 |
+
async with httpx.AsyncClient() as client:
|
22 |
+
# 转发请求到目标服务器
|
23 |
+
response = await client.request(
|
24 |
+
method=request.method,
|
25 |
+
url=target_url,
|
26 |
+
params=url_params,
|
27 |
+
headers={key: value for key, value in request.headers.items() if key != "host"},
|
28 |
+
content=await request.body(),
|
29 |
+
)
|
30 |
+
|
31 |
+
# 返回目标服务器的响应
|
32 |
+
return StreamingResponse(
|
33 |
+
content=response.aiter_bytes(),
|
34 |
+
status_code=response.status_code,
|
35 |
+
headers=response.headers,
|
36 |
+
)
|
37 |
+
|
38 |
+
@app.websocket("/{path:path}")
|
39 |
+
async def websocket_proxy(websocket: WebSocket, path: str):
|
40 |
+
await websocket.accept()
|
41 |
+
|
42 |
+
# 构建目标WebSocket URL
|
43 |
+
target_url = f"ws://localhost:{TARGET_PORT}/{path}"
|
44 |
+
|
45 |
+
# 连接到目标WebSocket服务器
|
46 |
+
async with websockets.connect(target_url) as target_websocket:
|
47 |
+
# 创建两个任务来转发消息
|
48 |
+
forward_task = asyncio.create_task(forward_messages(websocket, target_websocket))
|
49 |
+
reverse_task = asyncio.create_task(reverse_messages(websocket, target_websocket))
|
50 |
+
|
51 |
+
# 等待两个任务完成
|
52 |
+
await asyncio.gather(forward_task, reverse_task)
|
53 |
+
|
54 |
+
async def forward_messages(source: WebSocket, target: websockets.WebSocketClientProtocol):
|
55 |
+
try:
|
56 |
+
while True:
|
57 |
+
message = await source.receive_text()
|
58 |
+
await target.send(message)
|
59 |
+
except websockets.ConnectionClosed:
|
60 |
+
pass
|
61 |
+
|
62 |
+
async def reverse_messages(source: WebSocket, target: websockets.WebSocketClientProtocol):
|
63 |
+
try:
|
64 |
+
while True:
|
65 |
+
message = await target.recv()
|
66 |
+
await source.send_text(message)
|
67 |
+
except websockets.ConnectionClosed:
|
68 |
+
pass
|
69 |
+
|
70 |
+
if __name__ == "__main__":
|
71 |
+
import uvicorn
|
72 |
+
uvicorn.run(app, host="0.0.0.0", port=PROXY_PORT)
|