2016-08-28 14:43:00 +03:00
|
|
|
# Python rough implementation of a C# TCP client
|
2016-08-26 13:58:53 +03:00
|
|
|
import socket
|
2016-09-09 12:47:37 +03:00
|
|
|
import time
|
2016-10-03 10:53:41 +03:00
|
|
|
from datetime import datetime, timedelta
|
2017-05-09 20:01:44 +03:00
|
|
|
from threading import Event, Lock
|
2016-09-09 12:47:37 +03:00
|
|
|
|
2016-09-17 21:42:34 +03:00
|
|
|
from telethon.errors import ReadCancelledError
|
|
|
|
from telethon.utils import BinaryWriter
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
|
|
|
|
class TcpClient:
|
2017-03-20 19:16:34 +03:00
|
|
|
def __init__(self, proxy=None):
|
2016-08-26 13:58:53 +03:00
|
|
|
self.connected = False
|
2017-05-20 12:34:23 +03:00
|
|
|
self.proxy = proxy
|
|
|
|
self._recreate_socket()
|
2017-05-09 20:05:14 +03:00
|
|
|
|
2017-05-20 12:34:23 +03:00
|
|
|
# Support for multi-threading advantages and safety
|
|
|
|
self.cancelled = Event() # Has the read operation been cancelled?
|
|
|
|
self.delay = 0.1 # Read delay when there was no data available
|
|
|
|
self.lock = Lock()
|
|
|
|
|
|
|
|
def _recreate_socket(self):
|
|
|
|
self.socket = None
|
|
|
|
if self.proxy:
|
2017-03-20 19:16:34 +03:00
|
|
|
try:
|
|
|
|
import socks
|
|
|
|
self.socket = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM)
|
2017-05-20 12:34:23 +03:00
|
|
|
self.socket.set_proxy(*self.proxy)
|
2017-03-20 19:16:34 +03:00
|
|
|
except (ImportError, SystemError):
|
|
|
|
print("Can't import PySocks, fallback to vanilla socket. "
|
|
|
|
"Proxy settings are ignored. "
|
|
|
|
"Try to install PySocks via pip")
|
2017-05-09 20:05:14 +03:00
|
|
|
|
2017-05-20 12:34:23 +03:00
|
|
|
if not self.socket:
|
2017-03-20 19:16:34 +03:00
|
|
|
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
2016-09-10 11:17:15 +03:00
|
|
|
|
2016-08-26 13:58:53 +03:00
|
|
|
def connect(self, ip, port):
|
2016-08-28 14:43:00 +03:00
|
|
|
"""Connects to the specified IP and port number"""
|
2017-04-29 21:57:08 +03:00
|
|
|
if not self.connected:
|
|
|
|
self.socket.connect((ip, port))
|
|
|
|
self.connected = True
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
def close(self):
|
2016-08-28 14:43:00 +03:00
|
|
|
"""Closes the connection"""
|
2017-04-29 21:57:08 +03:00
|
|
|
if self.connected:
|
|
|
|
self.socket.close()
|
|
|
|
self.connected = False
|
2017-05-20 12:34:23 +03:00
|
|
|
self._recreate_socket()
|
2016-08-26 13:58:53 +03:00
|
|
|
|
|
|
|
def write(self, data):
|
2016-08-28 14:43:00 +03:00
|
|
|
"""Writes (sends) the specified bytes to the connected peer"""
|
2016-09-10 11:17:15 +03:00
|
|
|
|
|
|
|
# Ensure that only one thread can send data at once
|
|
|
|
with self.lock:
|
2016-09-16 17:37:45 +03:00
|
|
|
# Set blocking so it doesn't error
|
|
|
|
self.socket.setblocking(True)
|
|
|
|
self.socket.sendall(data)
|
2016-08-26 13:58:53 +03:00
|
|
|
|
2016-10-03 10:53:41 +03:00
|
|
|
def read(self, buffer_size, timeout=timedelta(seconds=5)):
|
|
|
|
"""Reads (receives) the specified bytes from the connected peer.
|
|
|
|
A timeout can be specified, which will cancel the operation if no data
|
|
|
|
has been read in the specified time. If data was read and it's waiting
|
|
|
|
for more, the timeout will NOT cancel the operation. Set to None for no timeout"""
|
2016-09-09 12:47:37 +03:00
|
|
|
|
2016-09-10 11:17:15 +03:00
|
|
|
# Ensure that only one thread can receive data at once
|
|
|
|
with self.lock:
|
|
|
|
# Ensure it is not cancelled at first, so we can enter the loop
|
2017-05-09 20:01:44 +03:00
|
|
|
self.cancelled.clear()
|
2016-09-10 11:17:15 +03:00
|
|
|
|
2016-09-16 17:37:45 +03:00
|
|
|
# Set non-blocking so it can be cancelled
|
|
|
|
self.socket.setblocking(False)
|
|
|
|
|
2016-10-03 10:53:41 +03:00
|
|
|
# Set the starting time so we can calculate whether the timeout should fire
|
|
|
|
if timeout:
|
|
|
|
start_time = datetime.now()
|
|
|
|
|
2016-09-10 11:17:15 +03:00
|
|
|
with BinaryWriter() as writer:
|
2016-09-11 12:50:38 +03:00
|
|
|
while writer.written_count < buffer_size:
|
|
|
|
# Only do cancel if no data was read yet
|
|
|
|
# Otherwise, carry on reading and finish
|
2017-05-09 20:01:44 +03:00
|
|
|
if self.cancelled.is_set() and writer.written_count == 0:
|
2016-09-11 12:50:38 +03:00
|
|
|
raise ReadCancelledError()
|
|
|
|
|
2016-09-10 11:17:15 +03:00
|
|
|
try:
|
|
|
|
# When receiving from the socket, we may not receive all the data at once
|
|
|
|
# This is why we need to keep checking to make sure that we receive it all
|
|
|
|
left_count = buffer_size - writer.written_count
|
|
|
|
partial = self.socket.recv(left_count)
|
2017-05-20 11:34:05 +03:00
|
|
|
if len(partial) == 0:
|
|
|
|
raise ConnectionResetError(
|
|
|
|
'The server has closed the connection (recv() returned 0 bytes).')
|
2016-09-10 11:17:15 +03:00
|
|
|
writer.write(partial)
|
2016-09-09 12:47:37 +03:00
|
|
|
|
2017-05-19 08:48:01 +03:00
|
|
|
except BlockingIOError as error:
|
2016-09-10 11:17:15 +03:00
|
|
|
# There was no data available for us to read. Sleep a bit
|
|
|
|
time.sleep(self.delay)
|
2016-09-09 12:47:37 +03:00
|
|
|
|
2016-10-03 10:53:41 +03:00
|
|
|
# Check if the timeout finished
|
|
|
|
if timeout:
|
|
|
|
time_passed = datetime.now() - start_time
|
|
|
|
if time_passed > timeout:
|
2016-11-30 00:29:42 +03:00
|
|
|
raise TimeoutError(
|
2017-05-19 08:48:01 +03:00
|
|
|
'The read operation exceeded the timeout.') from error
|
2016-10-03 10:53:41 +03:00
|
|
|
|
2016-09-10 11:17:15 +03:00
|
|
|
# If everything went fine, return the read bytes
|
|
|
|
return writer.get_bytes()
|
2016-09-09 12:47:37 +03:00
|
|
|
|
|
|
|
def cancel_read(self):
|
2016-09-11 12:50:38 +03:00
|
|
|
"""Cancels the read operation IF it hasn't yet
|
|
|
|
started, raising a ReadCancelledError"""
|
2017-05-09 20:01:44 +03:00
|
|
|
self.cancelled.set()
|