Files
@ 4e5f76c966dc
Branch filter:
Location: Morevna/src/networkers.py - annotation
4e5f76c966dc
1.6 KiB
text/x-python
indentation: spaces->tabs
59339cfb3d80 59339cfb3d80 59339cfb3d80 59339cfb3d80 59339cfb3d80 59339cfb3d80 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 59339cfb3d80 59339cfb3d80 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc 4e5f76c966dc | import threading
import queue
import json
class NetworkReader(threading.Thread):
def __init__(self,stream):
threading.Thread.__init__(self,daemon=True)
self.parent=threading.current_thread()
self.stream=stream
self.output=queue.Queue()
def run(self):
while True:
if not self.parent.is_alive(): return
self.output.put(self.readMsg(),timeout=2)
def readMsg(self):
data=self.stream.readline()
if not data: pass # !! raise something
jsonLength=int(data.split(b":")[1].strip()) # "json-length: length" -> length
data=self.stream.readline()
if not data: pass # !! raise something
binLength=int(data.split(b":")[1].strip()) # "bin-length: length" -> length
jsonData=self.stream.read(jsonLength)
jsonData=json.loads(str(jsonData,encoding="utf-8"))
binData=self.stream.read(binLength)
return (jsonData,binData)
class NetworkWriter(threading.Thread):
def __init__(self,stream):
threading.Thread.__init__(self,daemon=True)
self.parent=threading.current_thread()
self.stream=stream
self.input=queue.Queue()
def run(self):
while True:
if not self.parent.is_alive(): return
msg=self.input.get(timeout=2)
if msg is None: return
self.stream.write(self.writeMsg(msg))
self.stream.flush()
def writeMsg(self,msg):
jsonData,binData=msg
jsonData=bytes(json.dumps(jsonData)+"\n",encoding="utf-8")
jsonLength=bytes("json-length: "+str(len(jsonData))+"\n",encoding="utf-8")
binLength=bytes("bin-length: "+str(len(binData))+"\n",encoding="utf-8")
return b"".join((jsonLength,binLength,jsonData,binData))
|