I am trying to establish a connection between a Python server code that generate data and a javascript client that display it.
All answer that I see are by redefining some class and you need quiet some knowledge in network to do this.
I see this problem as a simple utilisation of websocket so I guess their is some simple utilisation I am not seeing without having to use classes...
my problem can be reduced at this code :
# definition of the websocket
application = web.Application([(r'/websocket',WebSocketHandler)])
application.listen(8001)
while True:
val = generate_data()
application.send(val) #it's this part that i miss
The real problem here is that my function generate_data()
is a bit complicated and display some stuff, now passing it in a function of the class WShandler(..)
is just not the right approach it's complicated and most of all not working. Further more the timing of when to send the data must be handle by my while loop not by some timeout that I will define.
Using the library websocket-server https://github.com/Pithikos/python-websocket-server it is possible
you just have to redifine the function run_forever
in websocket server.py from :
logger.info("Listening on port %d for clients.." % self.port)
self.serve_forever()
to :
logger.info("Listening on port %d for clients.." % self.port)
# self.serve_forever()
_serve = self.serve_forever
server_thread = threading.Thread(target=_serve)
# server_thread.daemon = True
server_thread.start()
After in your code:
r = WebsocketServer(8001, host='localhost', loglevel=logging.INFO)
server.run_forever()
while True:
val = generate_data()
server.send_message_to_all(val)
And it works like a charm. Maybe their is a way to do the same with tornado..
source:
https://github.com/Pithikos/python-websocket-server/issues/30
Threaded, non-blocking websocket client