Reputation: 5
Not getting response from tornado server while testing with infinite loop
Client :
from ws4py.client.tornadoclient import TornadoWebSocketClient
from tornado import ioloop
import random
import time
import itertools
class MyClient(TornadoWebSocketClient):
def opened(self):
#for i in range(0,100000):
#for i in itertools.count():
while 1:
test=random.choice('0123456789')
self.send(test)
time.sleep(2)
def received_message(self, m):
print(m)
if len(m) == 175:
self.close(reason='Bye bye')
def closed(self, code, reason=None):
ioloop.IOLoop.instance().stop()
ws = MyClient('ws://localhost:9001', protocols=['http-only', 'chat'])
ws.connect()
ioloop.IOLoop.instance().start()
This is the server code using tornado server. I am able to get the response from server when using finite loop but not getting any response on my client when I test it with infinite loop.
Server :
# !/usr/bin/python
# import the libraries
import tornado.web
import tornado.websocket
import tornado.ioloop
import os
# This is our WebSocketHandler - it handles the messages
# from the tornado server
class WebSocketHandler(tornado.websocket.WebSocketHandler):
# the client connected
def open(self):
print("New cient connected to server")
# self.write_message("You are connected to server")
# the client sent the message
def on_message(self, message):
# self.write_message(" from server ")
self.write_message(message + " received on server ")
# client disconnected
def on_close(self):
print("Client disconnected")
# start a new WebSocket Application
# use "/" as the root, and the
# WebSocketHandler as our handler
application = tornado.web.Application([
(r"/", WebSocketHandler),
])
# start the tornado server on port 8888
if __name__ == "__main__":
application.listen(9001)
tornado.ioloop.IOLoop.instance().start()
Upvotes: 0
Views: 779
Reputation: 24007
Never call sleep
from a Tornado application; it blocks the main thread and prevents any work from proceeding. Instead you want something like:
class MyClient(TornadoWebSocketClient):
periodic_callback = None
def opened(self):
# period is in milliseconds.
self.periodic_callback = ioloop.PeriodicCallback(self.send_random,
2000)
def send_random(self):
test = random.choice('0123456789')
self.send(test)
def closed(self, code, reason=None):
self.periodic_callback.stop()
Upvotes: 1