python websocket 再線聊天室的 Demo

服務端javascript

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

客戶端css

<!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>
相關文章
相關標籤/搜索