1. 程式人生 > >tornado websocket程式設計(1) 初識websocket ——簡單購物車實現

tornado websocket程式設計(1) 初識websocket ——簡單購物車實現

tornado websocket程式設計 : 初識websocket ——簡單購物車實

  • app.py 基本結構(或者說是一個手腳架吧,一步一步的新增我們需要的功能)
#!/usr/bin/env python
# -*-coding:utf-8-*-

import os.path

import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import tornado.options


class Application(tornado.web.Application)
:
def __init__(self): handlers = [ ] settings = { 'debug': True, 'template_path': os.path.join(os.path.dirname(__file__), 'templates'), 'static_path': os.path.join(os.path.dirname(__file__), 'static'
) } tornado.web.Application.__init__(self, handlers, **settings) if __name__ == '__main__': tornado.options.parse_command_line() app = Application() server = tornado.httpserver.HTTPServer(app) server.listen(8000) tornado.ioloop.IOLoop.instance().start()

重寫tornado.web.Application用以

新增一個全域性的Cart類例項
Cart類則以觀察者模式用來註冊每個websocket連線

  • websocket handler 原型
class CartStatusHandler(tornado.1websocket.WebSocketHandler):
    def open(self):
        pass

    def on_close(self):
        pass

    def on_message(self, message):
        pass


- 編寫Cart類原型,用來註冊websocket連線,
通過迭代已註冊的連線列表中的回撥函式向客戶端返回訊息

class Cart(object):
    callbacks = []

    def __init__(self):
        self.__total = 100

    def register(self, callback):
        self.callbacks.append(callback)

    def unregister(self, callback):
        self.callbacks.remove(callback)

    @property
    def total(self):
        return self.__total

    def notify(self):
        for callback in self.callbacks:
            callback(self.__total)


- 在Application類中新增一個全域性Cart例項

class Application(tornado.web.Application):
    def __init__(self):

        self.cart = Cart()

        handlers = [
        ]

        settings = {
            'debug': True,
            'template_path': os.path.join(os.path.dirname(__file__),
                                          'templates'),
            'static_path': os.path.join(os.path.dirname(__file__),
                                        'static')
        }

        tornado.web.Application.__init__(self, handlers, **settings)
  • 修改CartStatusHandler類
    WebSocket連線關聯到Cart: 註冊、取消註冊以及訊息推送回調函式
class CartStatusHandler(tornado.1websocket.WebSocketHandler):
    def open(self):
        self.application.cart.register(self.callback)

    def on_close(self):
        self.application.cart.unregister(self.callback)

    def on_message(self, message):
        pass

    def callback(self, count):
        self.write_message('{"count" :%d}' %count)

到這一步基本websocket後端邏輯實現了
現在開始準備一個前後端通訊的場景

  • 實現Cart Index
class Index(tornado.web.RequestHandler):
    def get(self):
        context = {
            'total': self.application.cart.total
        }
        self.render('cart.html', **context)

    def post(self):
        action = self.get_argument('action')

        if action == 'add':
            self.add_order()
        elif action == 'remove':
            self.cancel_order()
        else:
            self.set_status(400)

    def add_order(self):
        self.application.cart.add_order()
        self.write('success')

    def cancel_order(self):
        self.application.cart.cancel_order()
        self.write('success')
  • 前端準備

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <p>Test websocket</p>
    <script src="http://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
    <script src="/static/built/ex1_websocket.js"></script>
</body>
</html>

js

$(function() {
    var goodsClient = new WebSocket('ws://127.0.0.1:8000/websocket_goods');

    goodsClient.onopen = function(e) {
        console.log('connected');
    }

    goodsClient.onmessage = function(e) {
        // 接受websocket訊息
        var data = null,
            message  = { data: data };

        try {
            message.data = JSON.parse(evt.data);
        } catch (e) {
            message.data = evt;
        }

        $("#total").text(message.data.count);
    }

    $("button#add").on("click", function () {
        //新增貨物
        $.ajax({
            'url': '/',
            'type': 'POST',
            'dataType': 'json',
            'data': { 'action': 'add' }
        });
    });


    $("button#del").on("click", function () {
        //取消新增
        $.ajax({
            'url': '/',
            'type': 'POST',
            'dataType': 'json',
            'data': { 'action': 'remove' }
        });
    });
});