80 lines
2.6 KiB
Python
80 lines
2.6 KiB
Python
# -*- coding: utf-8 -*-
|
|
import os
|
|
import json
|
|
import random
|
|
import time
|
|
import threading
|
|
from tornado import ioloop
|
|
from tornado import gen
|
|
from tornado.websocket import websocket_connect
|
|
from tornado.tcpclient import TCPClient
|
|
|
|
class ClientSide:
|
|
|
|
def __init__(self, local_ip, remote_ip):
|
|
self._local_ip = local_ip
|
|
self._remote_ip = remote_ip
|
|
self.local_conn = None
|
|
self.local_read_future = None
|
|
self.remote_conn = None
|
|
|
|
@gen.coroutine
|
|
def co_connect2(self):
|
|
while True:
|
|
if not self.local_conn:
|
|
[local_host, local_port] = self._local_ip.split(':')
|
|
self.local_conn = yield TCPClient().connect(local_host, local_port)
|
|
if not self.remote_conn:
|
|
[remote_host, remote_port] = self._remote_ip.split(':')
|
|
url = 'ws://%s:%s/websocket' % (remote_host, remote_port)
|
|
self.remote_conn = yield websocket_connect(url)
|
|
|
|
if self.local_conn and not self.local_read_future:
|
|
print('ok1')
|
|
self.local_read_future = self.local_conn.read_until(b"\n")
|
|
print('ok')
|
|
|
|
if self.local_read_future:
|
|
self.local_read_future.fetch_next_chunk()
|
|
|
|
@gen.coroutine
|
|
def co_localConnect(self):
|
|
[local_host, local_port] = self._local_ip.split(':')
|
|
self.local_conn = yield TCPClient().connect(local_host, local_port)
|
|
|
|
@gen.coroutine
|
|
def co_remoteConnect(self):
|
|
[remote_host, remote_port] = self._remote_ip.split(':')
|
|
url = 'ws://%s:%s/websocket' % (remote_host, remote_port)
|
|
self.remote_conn = yield websocket_connect(url)
|
|
data = ''
|
|
while True:
|
|
data += yield self.remote_conn.read_message()
|
|
lines = data.split('\n')
|
|
if data[-1] == '\n':
|
|
data = lines[-1]
|
|
lines = lines[:-1]
|
|
for line in lines:
|
|
print(line)
|
|
msg = json.loads(line)
|
|
self.dispatchRemoteMsg(msg)
|
|
|
|
def dispatchRemoteMsg(self, msg):
|
|
if msg['cmd'] == 'connect':
|
|
ioloop.IOLoop.current().spawn_callback(self.co_localConnect)
|
|
elif msg['cmd'] == 'socketClose':
|
|
pass
|
|
elif msg['cmd'] == 'forwardData':
|
|
pass
|
|
|
|
@gen.coroutine
|
|
def co_connect(self):
|
|
# ioloop.IOLoop.current().spawn_callback(self.co_localConnect)
|
|
ioloop.IOLoop.current().spawn_callback(self.co_remoteConnect)
|
|
while True:
|
|
yield gen.sleep(0.1)
|
|
|
|
def run(self):
|
|
ioloop.IOLoop.current().run_sync(self.co_connect)
|
|
|