Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

Python mutiprocessing with socket

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...