• 基于tornado实现的web聊天室


    目录结构:

    # -*- coding:utf-8 -*-
    import uuid
    import json
    import tornado.ioloop
    import tornado.web
    import tornado.websocket
    
    
    class IndexHandler(tornado.web.RequestHandler):
        def get(self):
            self.render('index.html')
    
    
    class ChatHandler(tornado.websocket.WebSocketHandler):
        # 用户存储当前聊天室用户
        waiters = set()
        # 用于存储历时消息
        messages = []
    
        def open(self):
            """
            客户端连接成功时,自动执行
            :return: 
            """
            ChatHandler.waiters.add(self)
            uid = str(uuid.uuid4())
            self.write_message(uid)
    
            for msg in ChatHandler.messages:
                content = self.render_string('message.html', **msg)
                self.write_message(content)
    
        def on_message(self, message):
            """
            客户端连发送消息时,自动执行
            :param message: 
            :return: 
            """
            msg = json.loads(message)
            ChatHandler.messages.append(msg)
    
            for client in ChatHandler.waiters:
                content = client.render_string('message.html', **msg)
                client.write_message(content)
    
        def on_close(self):
            """
            客户端关闭连接时,,自动执行
            :return: 
            """
            ChatHandler.waiters.remove(self)
    
    
    def run():
        settings = {
            'template_path': 'templates',
            'static_path': 'static',
        }
        application = tornado.web.Application([
            (r"/", IndexHandler),
            (r"/chat", ChatHandler),
        ], **settings)
        application.listen(8888,address='0.0.0.0')
        tornado.ioloop.IOLoop.instance().start()
    
    
    if __name__ == "__main__":
        run()
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Python聊天室</title>
    </head>
    <body>
        <div>
            <input type="text" id="txt"/>
            <input type="button" id="btn" value="提交" onclick="sendMsg();"/>
            <input type="button" id="close" value="关闭连接" onclick="closeConn();"/>
        </div>
        <div id="container" style="border: 1px solid #dddddd;margin: 20px;min-height: 500px;">
    
        </div>
    
        <script src="/static/jquery-2.1.4.min.js"></script>
        <script type="text/javascript">
            $(function () {
                wsUpdater.start();
            });
    
            var wsUpdater = {
                socket: null,
                uid: null,
                start: function() {
                    var url = "ws://192.168.20.200:8888/chat";
                    wsUpdater.socket = new WebSocket(url);
                    wsUpdater.socket.onmessage = function(event) {
    
                        if(wsUpdater.uid){
                            wsUpdater.showMessage(event.data);
                        }else{
                            wsUpdater.uid = event.data;
                        }
                    }
                },
                showMessage: function(content) {
                    $('#container').append(content);
                }
            };
    
            function sendMsg() {
                var msg = {
                    uid: wsUpdater.uid,
                    message: $("#txt").val()
                };
                wsUpdater.socket.send(JSON.stringify(msg));
           $("#txt").val("") }
    </script> </body> </html>
    <div style="border: 1px solid #dddddd;margin: 10px;">
        <div>游客{{uid}}</div>
        <div style="margin-left: 20px;">{{message}}</div>
    </div>
  • 相关阅读:
    Linux tcpdump命令详解
    移动开发网站收集
    Struts+2权威指南基于WebWork核心的MVC开发源码下载
    Eclipse+php插件+Xdebug搭建PHP完美开发/调试环境指南
    java相对目录和绝对目录解析
    python学习网站搜集
    window下开发iphone程序环境搭建iphone tool chain
    Windows下编译objectiveC
    java class路径获取
    完全优化MySQL数据库性能的八个方法
  • 原文地址:https://www.cnblogs.com/52-qq/p/8530893.html
Copyright © 2020-2023  润新知