youandme/src/youandme/server.py

43 lines
1.3 KiB
Python
Raw Normal View History

2020-04-16 11:41:49 +00:00
import socket
import time
from threading import Thread
import typing
if typing.TYPE_CHECKING:
from stem.control import Controller
2020-04-20 08:36:41 +00:00
from.commands import garbage_character
2020-04-16 11:41:49 +00:00
def server(delay: int, controller: 'Controller', socket_conn, send_data: bytearray, recv_data: bytearray, connection: "Connection"):
2020-04-20 08:36:41 +00:00
def send_loop():
2020-04-16 11:41:49 +00:00
while True:
2020-04-20 08:36:41 +00:00
time.sleep(delay)
try:
if not send_data:
socket_conn.sendall(garbage_character)
2020-04-20 08:36:41 +00:00
else:
char = send_data.pop(0)
try:
socket_conn.sendall(ord(char))
2020-04-20 08:36:41 +00:00
except TypeError:
try:
socket_conn.sendall(char)
2020-04-20 08:36:41 +00:00
except TypeError:
socket_conn.sendall(chr(char).encode('utf-8'))
2020-04-20 08:36:41 +00:00
except OSError:
connection.connected = False
with socket_conn:
2020-04-20 08:36:41 +00:00
Thread(target=send_loop, daemon=True).start()
while True:
2020-04-20 11:15:19 +00:00
try:
data = socket_conn.recv(1)
2020-04-20 11:15:19 +00:00
except ConnectionResetError:
connection.connected = False
2020-04-20 11:15:19 +00:00
break
2020-04-20 08:36:41 +00:00
if not data: break
2020-04-20 08:36:41 +00:00
if data != garbage_character and data:
for i in data:
recv_data.append(i)