用Python写一个类似frp的 反向代理程序。本地网页127.0.0.1:8899,以及云端服务器公网访问的网页7.120.52.14:8080
时间: 2024-04-16 12:24:28 浏览: 166
可以使用Python的socket模块和多线程来实现一个简单的反向代理程序。以下是一个示例代码:
```python
import socket
import threading
class ReverseProxy:
def __init__(self, local_host, local_port, remote_host, remote_port):
self.local_host = local_host
self.local_port = local_port
self.remote_host = remote_host
self.remote_port = remote_port
def start(self):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((self.local_host, self.local_port))
server_socket.listen(5)
print(f"Proxy server started on {self.local_host}:{self.local_port}")
while True:
client_socket, addr = server_socket.accept()
print(f"Accepted connection from {addr[0]}:{addr[1]}")
proxy_thread = threading.Thread(target=self.proxy_handler, args=(client_socket,))
proxy_thread.start()
def proxy_handler(self, client_socket):
remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote_socket.connect((self.remote_host, self.remote_port))
while True:
data = client_socket.recv(4096)
if len(data) == 0:
break
remote_socket.send(data)
remote_data = remote_socket.recv(4096)
if len(remote_data) == 0:
break
client_socket.send(remote_data)
client_socket.close()
remote_socket.close()
if __name__ == "__main__":
proxy = ReverseProxy("127.0.0.1", 8899, "7.120.52.14", 8080)
proxy.start()
```
这段代码创建了一个名为ReverseProxy的类,它初始化了本地和远程主机以及端口。start()方法启动了代理服务器,监听本地主机和端口,接受客户端连接。proxy_handler()方法处理代理逻辑,将客户端请求发送到远程主机,并将远程主机的响应发送回客户端。
你可以将本地主机和端口设置为127.0.0.1:8899,将远程主机和端口设置为7.120.52.14:8080。然后运行这个程序,它将会将本地网页127.0.0.1:8899上的请求转发到云端服务器公网访问的网页7.120.52.14:8080上。
阅读全文