fstream/client/util/fstream-util-pipe_to_tcp.py

79 lines
1.7 KiB
Python
Raw Normal View History

2021-04-20 14:35:56 +00:00
#!/usr/bin/env python3
import sys
oldexcepthook = sys.excepthook
def newexcepthook(type,value,traceback):
oldexcepthook(type,value,traceback)
#input("Press ENTER to quit.")
sys.excepthook = newexcepthook
import os
p = os.path.join
pUp = os.path.dirname
s = False
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
s = os.path.realpath(sys.executable)
else:
s = os.path.realpath(__file__)
sp = pUp(s)
# script start
import socket
import threading
import queue
bufferSize = 1000
2021-04-20 14:35:56 +00:00
2021-04-21 10:57:19 +00:00
def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs)
2021-04-20 14:35:56 +00:00
connection = False
connectionLock = threading.Lock()
class pipeThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
2021-04-21 10:57:19 +00:00
global connection
2021-04-20 14:35:56 +00:00
while True:
data = sys.stdin.buffer.read(bufferSize)
2021-04-21 10:57:19 +00:00
with connectionLock:
try:
if type(connection) != bool:
connection.send(data)
except Exception as e:
connection = False
print(e)
2021-04-20 14:35:56 +00:00
2021-04-21 12:03:25 +00:00
def stringToAddressTuple(addr):
rtn = addr.rsplit(":",1)
rtn[1] = int(rtn[1])
rtn = tuple(rtn)
return rtn
def addressTupleToString(addr):
return ":".join(map(str,list(addr)))
serverAddr = stringToAddressTuple(sys.argv[1])
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
eprint("Opening socket...")
serverSocket.bind(serverAddr)
eprint("Serving on " +addressTupleToString(serverAddr)+ "!")
serverSocket.listen(1)
2021-04-20 14:35:56 +00:00
pThread = pipeThread()
pThread.start()
while True:
2021-04-21 10:57:19 +00:00
eprint("Awaiting connection...")
2021-04-20 14:35:56 +00:00
conn, address = serverSocket.accept()
2021-04-21 10:57:19 +00:00
eprint("Connection established, sending data.")
2021-04-20 14:35:56 +00:00
with connectionLock:
2021-04-21 10:32:52 +00:00
try:
2021-04-21 10:57:19 +00:00
if type(connection) != bool:
connection.close()
2021-04-21 10:32:52 +00:00
except Exception as e:
print(e)
2021-04-21 10:57:19 +00:00
2021-04-20 14:35:56 +00:00
connection = conn
2021-04-21 10:32:52 +00:00
connection.settimeout(15)