Skip to content

Instantly share code, notes, and snippets.

@grimpy
Last active February 29, 2020 12:47
Show Gist options
  • Save grimpy/c16f2421a43c5bbb25565c714fed9ce5 to your computer and use it in GitHub Desktop.
Save grimpy/c16f2421a43c5bbb25565c714fed9ce5 to your computer and use it in GitHub Desktop.
import gevent
from gevent.server import StreamServer
# we patch all
from gevent import monkey
monkey.noisy = False
monkey.patch_all()
import socket
import select
from functools import partial
BUFSIZE = 4096
# this handler will be run for each incoming connection in a dedicated greenlet
def copy(srcsocket, destsocket):
data = srcsocket.recv(BUFSIZE)
if not data:
srcsocket.close()
else:
destsocket.sendall(data)
def proxy_to(endpoint, clientsocket, address):
print("here..", address)
destsocket = socket.create_connection(endpoint)
while not clientsocket.closed and not destsocket.closed:
readable, writable, _ = select.select([clientsocket, destsocket], [], [], 1)
for ready_to_read in readable:
if ready_to_read == clientsocket:
print("Copying client to dest")
copy(clientsocket, destsocket)
elif ready_to_read == destsocket:
print("Copying dest to client")
copy(destsocket, clientsocket)
print("continuing...", clientsocket.closed, destsocket.closed)
clientsocket.close()
destsocket.close()
if __name__ == "__main__":
# to make the server use SSL, pass certfile and keyfile arguments to the constructor
dest = ("127.0.0.1", 8080)
handler = partial(proxy_to, dest)
server = StreamServer(("127.0.0.1", 16000), handler)
# to start the server asynchronously, use its start() method;
# we use blocking serve_forever() here because we have no other jobs
print("Starting proxy server on port 16000")
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment