基于Torando框架实现的WebSocket服务

栏目: Html5 · 发布时间: 8年前

内容简介:基于Torando框架实现的WebSocket服务

​ 项目中使用到了WebSocket技术,之前对WebSocket相关协议进行介绍,这里主要讲解如何借助一些第三方工具,实现一个WebSocket服务器。这里主要是基于Torando框架进行介绍,所以使用的库和示例也是围绕Tornado框架展开的,当然这里也会介绍一些其他的库。

​ 其实大部分的框架基本都是差不多的,只要通过集成WebSocket库,实现WebSocket通信核心的集合函数和事件,就可以完成一个WebSocket服务器。

WebSocket服务器实现

基于Torando自带模块实现

通过Tornado框架自带的WebSocket模块实现WebSocket服务器。相关的WebSocket文档可以在 Tornado框架之WebSocket文档 查看。

这里实现两个文件,进行WebSocket服务测试,ws_app.py 和index.html。

import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
 
class WebSocketHandler(tornado.websocket.WebSocketHandler):
    """
    	基于Torando的WebSocket实现,要继承'tornado.websocket.WebSocketHandler'
    	重写的三个函数的含义,可以参考上面的文档
    """
    def open(self):
        pass
 
    def on_message(self, message):
        self.write_message(u"Your message was: " + message)
 
    def on_close(self):
        pass
 
class IndexPageHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")
 
class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/', IndexPageHandler),
            (r'/websocket', WebSocketHandler)
        ]
        settings = {}
        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()
<!DOCTYPE html>
<html>
<head>
    <title>Tornado WebSockets</title>
    <script>
        var ws;
 
        function onLoad() {
            ws = new WebSocket("ws://localhost:8080/websocket");
            # 保持监听,对收到的消息进行处理
            ws.onmessage = function(e) {
               alert(e.data);
            };
        }
        function sendMsg() {
            # 发送消息
            ws.send(document.getElementById('msg').value);
        }
    </script>
</head>
<bodyonload="onLoad();">
    <strong>Message to Send:</strong> <inputtype="text"id="msg"maxlength="25"/>
     <inputtype="button"onclick="sendMsg();"value="Send"/>
</body>
</html>

访问 http://localhost:8080/

基于Torando框架实现的WebSocket服务

发送消息,观察控制台

基于Torando框架实现的WebSocket服务

基于第三方库(基于Torando模块进行开发)

Sockjs 是个非常棒的项目,这个项目基于多种语言和框架,开发了实现WebSocket服务的库,同时包括JS实现客户端。其中基于Tornado框架实现的项目是 sockjs-tornado

这里直接给出相关的示例代码,也是包含ws_app.py和index.html两个文件。

继续更新中。。。。。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Mechanics of Web Handling

The Mechanics of Web Handling

David R. Roisum

This unique book covers many aspects of web handling for manufacturing, converting, and printing. The book is applicable to any web including paper, film, foil, nonwovens, and textiles. The Mech......一起来看看 《The Mechanics of Web Handling》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具