SockJS 是要走的路:https ://github.com/mrjoes/sockjs-tornado
首先,准备好你的环境:
pip install sockjs-tornado
其次,您必须设置 Tornado:
application = django.core.handlers.wsgi.WSGIHandler()
container = tornado.wsgi.WSGIContainer(application)
tornado_app = tornado.web.Application(
EchoSockjsRouter('/websocket')+
[
('/source/([^/]+)', SourceHandler),
('.*', tornado.web.FallbackHandler, dict(fallback=container)),
]
)
HTTPServer(tornado_app).listen(port)
tornado.ioloop.IOLoop.instance().start()
'/source' 是一个请求处理程序(我使用它与 @gen.engine 进行异步),'.*' 适用于 Django,而 EchoSockjsRouter 是你想要的:
from sockjs.tornado import SockJSRouter, SockJSConnection
class EchoWebSocket(SockJSConnection):
def on_open(self, request):
print "sockjs: open"
def on_message(self, data):
print "data: %r" % (data,)
self.send(data)
def on_comment(self, data):
print "data: %r" % (data,)
self.send(data)
def on_close(self):
print "sockjs: close"
def EchoSockjsRouter(prefix):
return SockJSRouter(EchoWebSocket, prefix).urls
之后,您需要设置 UI(我使用的是 SockJS 客户端,版本 0.3.4,http ://sockjs.org,MIT许可证):
<script src="<SockJS Javascript>"></script>
<script>
socket = new SockJS('http://localhost:8000/websocket');
socket.onmessage = function(e) {
console.log(e.data);
};
socket.onclose = function() {
console.log('closed :(');
};
socket.onopen = function() {
console.log('opened :>');
letTheMadnessBegin();
};
function letTheMadnessBegin() {
// silly, but you get the idea
socket.send(JSON.stringify({
name: $('#name').text(),
message: $('input').val()
}));
}
<script>
好吧,你可以在 $(function(){}) 中制作漂亮的脚本......但除此之外,你已经准备好去:http ://grab.by/mSv6,http : //grab.by/mSuU(对不起404,这是为了让它变得现实Oo)。我从:https ://idea.popcount.org/2012-09-21-django-with-sockjs/
请注意,我尝试过使用Socketio、Tornado WebSocket和其他一些。然而 SocketJS 非常简单。
问候。