服务端

import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
import os
import datetime

from tornado.web import RequestHandler
from tornado.options import define, options
from tornado.websocket import WebSocketHandler

define("port", default=8000, type=int)

class IndexHandler(RequestHandler):
    def get(self):
        self.render("index.html")

class ChatHandler(WebSocketHandler):

    cli = set()  # 用来存放在线用户的容器

    def open(self):
        print(self.request)
        self.cli.add(self)  # 建立连接后添加用户到容器中
        for c in self.cli:  # 向已在线用户发送消息
            c.write_message(u"[%s]-[%s]-进入聊天室" % (self.request.remote_ip, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))

    def on_message(self, message):
        for c in self.cli:  # 向在线用户广播消息
            c.write_message(u"[%s]-[%s]-说:%s" % (self.request.remote_ip, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), message))

    def on_close(self):
        self.cli.remove(self) # 用户关闭连接后从容器中移除用户
        for c in self.cli:
            c.write_message(u"[%s]-[%s]-离开聊天室" % (self.request.remote_ip, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))

    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()

客户端

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>聊天室</title>
</head>
<style type="text/css">
    #char{
        margin: 0 auto;
        height:500px;
        width: 800px;
    }
    #contents{
        height:500px;
        width: 800px;
        border:1px solid #cccccc;
        border-radius:3px;
        box-shadow: 2px 2px 5px #888888;
        margin-bottom: 10px;
    }
    .input_send #msg{
        height:20px;
        width: 757px;
    }
</style>
<body>
    <div id="char" >
        <div id="contents"></div>
        <div class="input_send">
                <textarea id="msg"></textarea>
                <a href="javascript:;" id="send_mesage" onclick="sendMsg()">发送</a>
        </div>
    </div>
    <script src="{{static_url('js/jquery.min.js')}}"></script>
    <script type="text/javascript">
        var ws = new WebSocket("ws://192.168.199.182:9000/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>

 

posted on 2019-03-17 16:07  nike_9527  阅读(1526)  评论(0编辑  收藏  举报