I have following class for web-socket communication. Using it I have receive and send some data. But using mutiprocessing-module I need to use send from different process and recive from different process.
class WebsocketSignaling:
def __init__(self, host, port):
self._host = host
self._port = port
self._websocket = None
self.ssl_context = ssl._create_unverified_context()
async def connect(self):
try:
self._websocket = await websockets.connect("wss://" + str(self._host) + ":" + str(self._port),ssl=self.ssl_context)
return True
except Exception:
print("Cannot connect signaling Server--Exception")
await self.close()
return False;
async def close(self):
if self._websocket is not None and self._websocket.open is True:
await self._websocket.close()
async def receive(self):
try:
data = await self._websocket.recv()
except (ConnectionClosed):
print("---> asyncio.IncompleteReadError")
return None
return data
async def sendDirect(self, data):
await self._websocket.send(data + '
')
Main.py
from multiprocessing import Process, Queue
def receive(signaling):
while True:
obj = await signaling.receive()
print(obj)
def send(signaling):
while True:
msg = json.dumps({ "data": "hi"}, sort_keys=True)
await signaling.sendDirect(msg)
print("Sending")
if __name__ == '__main__':
signaling = create_signaling(args)
p1 = Process(target=receive, args=(signaling,))
p2 = Process(target=send, args=(signaling,))
p1.start()
p1.join()
p2.start()
p2.join()
Is it safe to use the socket this way, it it process safe.
question from:
https://stackoverflow.com/questions/65598555/python-mutiprocessing-with-socket 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…