One of the simplest servers
Python has the ability to start a single server listening port, using the wsgiref of the standard library.
From wsgiref.simple_server import make_server def simple_app (environ, start_response): status = ' OK ' Response_headers = [(' Content-type ', ' Text/plain ')] start_response (status, Response_headers)
50 lines of code to implement a proxy server
Before encountering a scenario like this:
I need a MongoDB graphics client on my computer, but MongoDB's server address is not open to the Internet, only by logging on to host A and then from a to MongoDB Server B.
I wanted to forward it through the SSH port, but I didn't have permission to connect SSH to B from machine A. So I wrote one in Python.
The principle is simple.
1. Open a socket server to listen for connection requests
2. For each client connection request, a connection request is created for the address to be forwarded. That is Client->proxy->forward. Proxy is both the socket server (listening client) and the socket client (toward forward request).
3. Bind the 2 sockets of Client->proxy and Proxy->forward in a dictionary.
4. Pass the SEND/RECV data intact through this mapped dictionary
The code below.
#coding =utf-8 Import Socket Import Select Import sys to_addr = (' xxx.xxx.xx.xxx ', 10000) #转发的地址 class Proxy:def __init __ (self, addr): Self.proxy = Socket.socket (socket.af_inet,socket. SOCK_STREAM) self.proxy.bind (addr) Self.proxy.listen (Ten) 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.soc Ket (socket.af_inet, socket. SOCK_STREAM) Forward.connect (to_addr) self.inputs + = [client, forward] self.route[client] = forward SELF.R Oute[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 () #代理服务器监听的地址 except KeyboardInterrupt:sys.exit (1)
The effect is as follows.