嘗試用最短的Python代碼來實現(xiàn)服務(wù)器和代理服務(wù)器
一個最簡單的服務(wù)器
Python擁有這種單獨起一個服務(wù)器監(jiān)聽端口的能力,用標準庫的wsgiref就行。
from wsgiref.simple_server import make_server
def simple_app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Hello world!\n']
httpd = make_server('', 80, simple_app)
httpd.serve_forever()

50行代碼實現(xiàn)代理服務(wù)器
之前遇到一個場景是這樣的:
我在自己的電腦上需要用mongodb圖形客戶端,但是mongodb的服務(wù)器地址沒有對外網(wǎng)開放,只能通過先登錄主機A,然后再從A連接mongodb服務(wù)器B。
本來想通過ssh端口轉(zhuǎn)發(fā)的,但是我沒有從機器A連接ssh到B的權(quán)限。于是就自己用Python寫一個。
原理很簡單。
1.開一個socket server監(jiān)聽連接請求
2.每接受一個客戶端的連接請求,就往要轉(zhuǎn)發(fā)的地址建一條連接請求。即client->proxy->forward。proxy既是socket服務(wù)端(監(jiān)聽client),也是socket客戶端(往forward請求)。
3.把client->proxy和proxy->forward這2條socket用字典給綁定起來。
4.通過這個映射的字典把send/recv到的數(shù)據(jù)原封不動的傳遞
下面上代碼。
#coding=utf-8
import socket
import select
import sys
to_addr = ('xxx.xxx.xx.xxx', 10000)#轉(zhuǎn)發(fā)的地址
class Proxy:
def __init__(self, addr):
self.proxy = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.proxy.bind(addr)
self.proxy.listen(10)
self.inputs = [self.proxy]
self.route = {}
def serve_forever(self):
print 'proxy listen...'
while 1:
readable, _, _ = select.select(self.inputs, [], [])
for self.sock in readable:
if self.sock == self.proxy:
self.on_join()
else:
data = self.sock.recv(8096)
if not data:
self.on_quit()
else:
self.route[self.sock].send(data)
def on_join(self):
client, addr = self.proxy.accept()
print addr,'connect'
forward = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
forward.connect(to_addr)
self.inputs += [client, forward]
self.route[client] = forward
self.route[forward] = client
def on_quit(self):
for s in self.sock, self.route[self.sock]:
self.inputs.remove(s)
del self.route[s]
s.close()
if __name__ == '__main__':
try:
Proxy(('',12345)).serve_forever()#代理服務(wù)器監(jiān)聽的地址
except KeyboardInterrupt:
sys.exit(1)
效果截圖如下。

相關(guān)文章
PyQt5中QSpinBox計數(shù)器的實現(xiàn)
這篇文章主要介紹了PyQt5中QSpinBox計數(shù)器的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
python用selenium打開瀏覽器后秒關(guān)閉瀏覽器的解決辦法
最近朋友在學(xué)Selenium的時候遇到一個問題,當執(zhí)行完selenium程序后,瀏覽器會閃退也就是自動關(guān)閉,這篇文章主要給大家介紹了關(guān)于python用selenium打開瀏覽器后秒關(guān)閉瀏覽器的解決辦法,需要的朋友可以參考下2023-07-07
Python使用scrapy抓取網(wǎng)站sitemap信息的方法
這篇文章主要介紹了Python使用scrapy抓取網(wǎng)站sitemap信息的方法,涉及Python框架scrapy的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-04-04

