Python编程:tornado实现WebSocket通讯
【摘要】 以下实例有点像广播通讯,支持多个客户端连接
代码参考别人的,稍微做了一点点修改
服务器端 websocket_demo.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from datetime import datetime
import os...
以下实例有点像广播通讯,支持多个客户端连接
代码参考别人的,稍微做了一点点修改
服务器端 websocket_demo.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from datetime import datetime
import os
import tornado
from tornado.options import define, options
from tornado.web import RequestHandler
from tornado.websocket import WebSocketHandler
# 设置服务器端口
define("port", default=2222, type=int)
class IndexHandler(RequestHandler): def get(self): self.render("chat-client.html")
class ChatHandler(WebSocketHandler): users = set() # 用来存放在线用户的容器 def open(self): # 建立连接后添加用户到容器中 self.users.add(self) # 向已在线用户发送消息 for user in self.users: remote_ip, port = self.request.connection.context.address now = datetime.now().strftime("%H:%M:%S") user.write_message("[{}][{}:{}]-进入聊天室".format(now, remote_ip, port)) def on_message(self, message): # 向在线用户广播消息 now = datetime.now().strftime("%H:%M:%S") remote_ip, port = self.request.connection.context.address for user in self.users: user.write_message("[{}][{}:{}] {}".format(now, remote_ip, port, message)) def on_close(self): # 用户关闭连接后从容器中移除用户 now = datetime.now().strftime("%H:%M:%S") remote_ip, port = self.request.connection.context.address self.users.remove(self) for user in self.users: user.write_message("[{}][{}:{}]-离开聊天室".format(now, remote_ip, port)) def check_origin(self, origin): return True # 允许WebSocket的跨域请求
if __name__ == '__main__': tornado.options.parse_command_line() app = tornado.web.Application([ (r"/", IndexHandler), (r"/chat", ChatHandler), ], static_path=os.path.join(os.path.dirname(__file__), "static"), template_path=os.path.join(os.path.dirname(__file__), "template"), debug=True ) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.current().start()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
客户端 template/chat-client.html
<!DOCTYPE html>
<html>
<head> <meta charset="utf-8"> <title>聊天室</title>
</head>
<body> <div id="contents" style="height:500px;overflow:auto;"></div> <div> <textarea id="msg"></textarea> <a href="javascript:;" onclick="sendMsg()">发送</a> </div>
<!-- jQuery -->
<script src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript"> var ws = new WebSocket("ws://127.0.0.1:2222/chat"); ws.onmessage = function(e) { $("#contents").append("<p>" + e.data + "</p>"); }; function sendMsg() { var msg = $("#msg").val(); ws.send(msg); $("#msg").val(""); }
</script>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
通讯效果,打开两个网页
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/90047794
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)