想法

前两天想看看django 长轮询或者是websocket的方案,发现都不太好使。 tornado很适合做这个工作,于是找了些资料,参照了做了个最简单demo,以便备用。

具体的概念就不说了,tornado没怎么用过,但是python的web框架入门起来都是基本相当,没什么难度,即使没用过,看懂还是挺容易的。

文件目录

[tornado]websocket 最简单demo-LMLPHP

代码清单

ws_app.py

#-*- encoding:utf-8 -*-
#2014-12-18
#author: orangleliu

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

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

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True

    def open(self):
        pass

    def on_message(self, message):
        self.write_message(u"Your message was: "+message)

    def on_close(self):
        pass

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/', IndexPageHandler),
            (r'/ws', WebSocketHandler)
        ]

        settings = { "template_path": "."}
        tornado.web.Application.__init__(self, handlers, **settings)

if __name__ == '__main__':
    ws_app = Application()
    server = tornado.httpserver.HTTPServer(ws_app)
    server.listen(8080)
    tornado.ioloop.IOLoop.instance().start()

'''
python ws_app.py
'''

index.html

<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
	<meta charset="UTF-8">
	<title>Tornado Websocket</title>
</head>
<script type="text/javascript">
	var ws;
	function onLoad(){
		ws = new WebSocket("ws://localhost:8080/ws");
		ws.onmessage = function(e){
			alert(e.data)
		}
	}

	function sendMsg(){
		ws.send(document.getElementById('msg').value);
	}
</script>
<body onload='onLoad();'>
	Message to send:   <input type="text" id="msg" />
	  <input type="button" onclick="sendMsg();" value="发送" />
</body>
</html>

遇到的问题

在websocket调试的时候总是出现403错误

解决办法:http://blog.csdn.net/orangleliu/article/details/42008423

实验结果

[tornado]websocket 最简单demo-LMLPHP

参考文章

http://www.giantflyingsaucer.com/blog/?p=4586

04-13 10:50