summaryrefslogtreecommitdiff
path: root/examples/twisted_portforward.py
blob: 95d22e58093107efbf347f05b8706e22af7aebe4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import sys
from twisted.internet import reactor
from eventlet.coros import event, spawn_link
from eventlet.twistedutil import join_reactor
from eventlet.twistedutil.protocol import GreenClientCreator, SpawnFactory, UnbufferedTransport

def forward(from_, to):
    try:
        while True:
            x = from_.recv()
            if not x:
                break
            print 'forwarding %s bytes' % len(x)
            to.write(x)
    finally:
        to.loseConnection()

def handler(local):
    remote = GreenClientCreator(reactor, UnbufferedTransport).connectTCP(remote_host, remote_port)
    error = event()
    a = spawn_link(forward, remote, local)
    b = spawn_link(forward, local, remote)
    a.wait()
    b.wait()

local_port, remote_host, remote_port = sys.argv[1:]
local_port = int(local_port)
remote_port = int(remote_port)
reactor.listenTCP(local_port, SpawnFactory(handler))
reactor.run()