0
votes

I'm trying to create a class which allows me to put data into it while a websocket connection is open, but i can't figure out how to make the main call to the class non-blocking. Can someone point me in the right direction?

Here is what I have so far (some extraneous code removed):

class Audio_Sender:

    def __init__(self,IP_Address):
        self.Remote_IP_Address = IP_Address
        self.audio_queue = queue.Queue(10) #Max of 10 items

    async def Connect(self):
        uri = "ws://127.0.0.1:8765"
        async with websockets.connect(uri) as websocket:

            await websocket.send(json_voice_start)    
            
            while self.status == "Run":
                if not self.audio_queue.empty():
                    audio_data = self.audio_queue.get()
                    await websocket.send(audio_data)

            #pull any remaing data out:
            while not self.audio_queue.empty():
                audio_data = self.audio_queue.get()
                await websocket.send(audio_data)

            await websocket.send(json_voice_stop)

            voice_response = await websocket.recv()
            message = json.loads(voice_response)
            print("\t- " + message["result"])


    async def run_connect(self):
        task = asyncio.create_task(self.Connect())
        while not task.done():
            print("Task is not Done")
            await asyncio.sleep(1)
            
    def go(self):
        asyncio.run(self.run_connect())

#Create the Audio Sender
A = Audio_Sender("127.0.0.1","r")

#Put some data into it's queue
A.audio_queue.put(b"abc")
A.audio_queue.put(b"abc")
A.audio_queue.put(b"abc")

#Finished putting data in
A.status = "Done"

#Now send the data
#Ideally I would like to have the go part way through the queuing of
# data (above), but A.go() is blocking.. how to make it not blocking?
A.go()

 
1
The entry point into asyncio must be blocking because it runs the event loop. What is non-blocking ("async") are the coroutines that run inside it, because they all cooperate inside a single thread, and each of them suspends instead of blocking, allowing the event loop to proceed. Your call to self.audio_queue.get() will cause problems because it's a blocking call. - user4815162342

1 Answers

0
votes

So playing with this a bit more I realized i could use a thread for the go(), which works:

Updated code is as follows:

#Create the Audio Sender
A = Audio_Sender("127.0.0.1","r")

s = threading.Thread(target=A.go,args=())
s.start()

i=0
while i<10:
    #Put some data into it's queue
    A.audio_queue.put(b"abc")
    i = i +1
    print(i)



#Finished putting data in
A.status = "Done"