tornado websocket 怎么区别每个连接的用户?


py:


 import logging
import os.path
import uuid
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket


def send_message(message):
    for handler in ChatSocketHandler.socket_handlers:
        try:
            handler.write_message(message)
        except:
            logging.error('Error sending message', exc_info=True)


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')


class ChatSocketHandler(tornado.websocket.WebSocketHandler):
    socket_handlers = set()
    num = 0
    def open(self):
        ChatSocketHandler.num = ChatSocketHandler.num + 1
        name = "name:%s" % ChatSocketHandler.num
        ChatSocketHandler.socket_handlers.add(self)
        send_message('A new user has entered the chat room.')

    def on_close(self):
        ChatSocketHandler.num = ChatSocketHandler.num - 1
        ChatSocketHandler.socket_handlers.remove(self)
        send_message('A user has left the chat room.')

    def on_message(self, message):
        send_message(message)


def main():
    application = tornado.web.Application([
        ('/', MainHandler),
        ('/new-msg/socket', ChatSocketHandler)
    ], debug=True)
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8000)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == '__main__':
    main()

html:


 <!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>{{title}}</title>
</head>
<body>
hello world


<div><button id="do">send</button></div>




<div id="con"></div>


</body>
<script src="http://jinri.info/common/js/jquery.min.js"></script>


<script>
    $(function() {
        $('#do').click(function() {
            sendMessage()
        })
        longMesaage()
    })
    //发送信息
    function sendMessage() {
        var url = "http://to.com/new/message"
        $.post(url, {con:'hello'});
    }
    //长连接,查看是否有新消息
    function longMesaage() {
        var url = "http://to.com/new/get"
        $.get(url, function(data) {
            $('#con').append("<div>"+data+"</div>");
            longMesaage()
        })
    }
</script>


</html>

这个一个简单的demo
我想改进下
页面上设置好用户名,然后每次发言的时候带上用户名
这个应该怎么改?

websocket python tornado

DEF湮灭 9 years, 10 months ago

用session。或者用cookie


 #!/usr/bin/env python
#coding:utf-8
# Author        : tuxpy
# Email         : [email protected]
# Last modified : 2015-08-13 15:08:17
# Filename      : chat.py
# Description   : 
from __future__ import print_function

from tornado import web, websocket, ioloop, options, escape

from tornado.options import define, options
from tornado.httpserver import HTTPServer

define('port', default = 8888, help = 'run on the given port', type = int)

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

class ChatHandler(websocket.WebSocketHandler):
    all_client = set()
    def open(self):
        nickname = escape.utf8(self.get_secure_cookie('nickname'))
        if not nickname:
            raise HTTPError(400)
        print('当前连接得是', nickname)
        self.nickname = nickname
        ChatHandler.all_client.add(self)

    def on_close(self):
        ChatHandler.all_client.remove(self)

    def on_message(self, message):
        message = "%s 说: %s" % (self.nickname, 
                escape.utf8(message))
        for client in ChatHandler.all_client:
            client.write_message(message)

class LoginHandler(web.RequestHandler):
    def post(self):
        nickname = self.get_body_argument('nickname', '').strip()
        if not nickname:
            raise web.HTTPError(400)

        self.set_secure_cookie('nickname', nickname)

class ChatApplication(web.Application):
    def __init__(self):
        handlers = [
                (r'/', IndexHandler),
                (r'/login', LoginHandler),
                (r'/chat', ChatHandler),
                ]

        settings = dict(
                cookie_secret = 'abc',
                template_path = 'template',
                static_path = 'static',
                debug = True,
                )

        web.Application.__init__(self, handlers, **settings)

if __name__ == "__main__":
    options.parse_command_line()
    app = ChatApplication()
    http_server = HTTPServer(app)
    http_server.listen(options.port)
    ioloop.IOLoop.instance().start()


上面是我写得demo,就是可以用cookie的。分成两部来做,第一步是登录,这时候把nickname存到cookie时,第二步当websocket open时,把cookie里的nickname取出来吧。

uillmm answered 9 years, 10 months ago

Your Answer