WebSocket with asyncio and messages from outside ?

#1

Hello All

I’m using WebSocket with asyncio, it works correctly, but I can’t send message from outside MyServerProtocol.

How to do this with eg. queue mechanism ?

I tried like this, but got error: object is not callable

In main:

q_in = queue.Queue()
factory.protocol = MyServerProtocol(q_in)

``

and in MyServerProtocol

class MyServerProtocol(WebSocketServerProtocol):
def init( self, queue ):
self.queue = queue

``

Second question is how to send message every 1s, I have while loop with self.connect_status, but in this case there is no onClose event, when the client disconnects, and this while loop is infinite.

class MyServerProtocol(WebSocketServerProtocol):
connect_status = False

def onConnect(self, request):
print(“Client connecting: {0}”.format(request.peer))
self.connect_status = True

def onOpen(self):
print(“WebSocket connection open.”)

while self.connect_status:
print(“Message PUT”)
time.sleep(1)

def onClose(self, wasClean, code, reason):
print(“WebSocket connection closed: {0}”.format(reason))
self.connect_status = False

``

0 Likes

#2

I can’t help you much with your first point. It is not clear to me what you are actually doing, more context is needed. Can you show a short concise example?

In your second question, that while loop would block the application from doing other things, such as running the event loop. You should look into creating a coroutine that sends your message and then does an asyncio.sleep(1.0). You would run this coroutine in an asyncio.Task(your_send_coroutine()). This kind of approach will not block the application and is the asyncio way.

Regards,

Chris

···

On Wednesday, July 23, 2014 10:22:23 PM UTC+9:30, omcdr wrote:

Hello All

I’m using WebSocket with asyncio, it works correctly, but I can’t send message from outside MyServerProtocol.

How to do this with eg. queue mechanism ?

I tried like this, but got error: object is not callable

In main:

q_in = queue.Queue()
factory.protocol = MyServerProtocol(q_in)

``

and in MyServerProtocol

class MyServerProtocol(WebSocketServerProtocol):
def init( self, queue ):
self.queue = queue

``

Second question is how to send message every 1s, I have while loop with self.connect_status, but in this case there is no onClose event, when the client disconnects, and this while loop is infinite.

class MyServerProtocol(WebSocketServerProtocol):
connect_status = False

def onConnect(self, request):
print(“Client connecting: {0}”.format(request.peer))
self.connect_status = True

def onOpen(self):
print(“WebSocket connection open.”)

while self.connect_status:
print(“Message PUT”)
time.sleep(1)

def onClose(self, wasClean, code, reason):
print(“WebSocket connection closed: {0}”.format(reason))
self.connect_status = False

``

0 Likes