WebSocket服务器在python中定期发送消息

编程入门 行业动态 更新时间:2024-10-24 18:26:34
本文介绍了WebSocket服务器在python中定期发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在python中有一个龙卷风Web服务器:

I have a tornado web server in python:

import tornado.httpserver import tornado.websocket import tornado.ioloop from tornado.ioloop import IOLoop import tornado.web import time import threading import sys from datetime import datetime from datetime import timedelta def sample(): print 'hiiiii' threading.Timer(10, sample).start() class WSHandler(tornado.websocket.WebSocketHandler): def open(self): print 'new connection' def on_message(self, message): self.write_message(message) self.msg('hellooooooo') print message def msg(self,message): self.write_message(message) threading.Timer(10, self.msg('in timer')).start() print 'in msg'+message def on_close(self): print 'connection closed' application = tornado.web.Application([ (r'/', WSHandler), ]) if __name__ == "__main__": http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8888) interval_ms=120 main_loop=tornado.ioloop.IOLoop.instance() main_loop.start()

客户是

<html> <head> <script> function fun(){ alert("in fun()"); var val=document.getElementById("txt"); var ws = new WebSocket("ws://localhost:8888"); ws.onopen = function(evt) { alert("Connection open ..."); ws.send(val.value); }; ws.onmessage = function(evt) { alert("from server: "+evt.data); } ws.onclose = function(evt) { alert("Connection closed."); } } </script> </head> <body bgcolor="#FFFFFF"> <input type="text" id="txt" /> <button onClick="fun()">click</button> </body> </html>

我想定期将消息发送给客户端.但是,当我尝试此操作时,出现以下错误:RunTimeError :Maximum Recursion Depth Exceeded.请帮助我解决此问题.另外,我们如何知道连接到服务器的客户端是什么?

I want to get the message periodically to the client. But when I try this I get this error: RunTimeError :Maximum Recursion Depth Exceeded. Please help me solve this issue. Also, how do we know what are the clients connected to the server?

推荐答案

以下是使用PeriodicCallback的最小示例.

Here's a minimal example using the PeriodicCallback.

import tornado.httpserver import tornado.websocket import tornado.ioloop from tornado.ioloop import PeriodicCallback import tornado.web class WSHandler(tornado.websocket.WebSocketHandler): def open(self): self.callback = PeriodicCallback(self.send_hello, 120) self.callback.start() def send_hello(self): self.write_message('hello') def on_message(self, message): pass def on_close(self): self.callback.stop() application = tornado.web.Application([ (r'/', WSHandler), ]) if __name__ == "__main__": http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8888) tornado.ioloop.IOLoop.instance().start()

更多推荐

WebSocket服务器在python中定期发送消息

本文发布于:2023-11-27 09:01:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637404.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送消息   服务器   WebSocket   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!