不用的代码,存一份--用tornado实现的websocket

因为现在使用Channels来实现啦,

这样就在Django的体系里自已弄完了。

方便后期代码维护和服务器部署。

这份土陋的东东,就放起来吧。

毕竟,通过读取文件来返回实时websocket,不适应于我的系统。

# coding:utf8
import tornado.ioloop
import tornado.web
import tornado.websocket
from tornado.ioloop import IOLoop
from datetime import timedelta
import time
import os
import sys
import tornado.httpserver

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    file_content = ""
    filename = "test.log"
    # 文件总大小,每次读取均更新长度
    f_size = 0
    # 每次读取的字节数,防止每次读得太多而卡死
    f_chunk = 1024
    # 文件读取指针位置
    f_pos = 0

    def check_origin(self, origin):
        return True

    def open(self):
        pass

    def update_client(self):
        self.write_message(self._read_file(self.filename))

    def on_message(self, message):
        self.filename = '-'.join(message.split('-')[1:])
        # 判断是否已存在LOG文件,如果没有,则先创建一个空文件内容
        if os.path.exists("/tmp/" + self.filename):
            self.update_client()
        else:
            with open("/tmp/" + self.filename, 'w') as f:
                f.write("empty file.....\n")

    def on_close(self):
        pass

    def _read_file(self, filename):
        '''
        f = open("/tmp/"+filename, "r")
        # seek里参数2是将指针放在末尾,检测文件长度
        f.seek(0, 2)
        self.f_size = f.tell()
        # 指针复位
        f.seek(self.f_pos, 0)
        # 判断文件长度是否大过单次读取字节
        if (self.f_size - self.f_pos) > self.f_chunk:
            ret_str = f.read(self.f_chunk)
            self.f_pos += self.f_chunk
            return ret_str
        else:
            # 如果(最后)一次可读取所有字节,则文件指针指到末尾,这是考虑可能下次再读时有新数据
            if self.f_size > self.f_pos:
                ret_str = f.read(self.f_size - self.f_pos)
                self.f_pos = self.f_size
                return ret_str
            elif self.f_size < self.f_pos:
                self.f_pos = 0
                return "reset"
            else:
                return ""
        f.close()
        '''
        with open("/tmp/"+filename) as f:
            content = f.read()
            if len(content) >= len(self.file_content):
                content_diff = content.replace(self.file_content, '')
                self.file_content = content
                return content_diff
            else:
                self.file_content = ""
                return "reset"

class IndexPageHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("websockets.html")

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/ws_log/', IndexPageHandler),
            (r'/websocket/ws', WebSocketHandler)
        ]
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            debug=True
        )
        tornado.web.Application.__init__(self, handlers, **settings)

if __name__ == '__main__':
    ws_app = Application()
    server = tornado.httpserver.HTTPServer(ws_app)
    server.listen(9527)
    tornado.ioloop.IOLoop.instance().start()
上一篇:【Dream Counting, 2006 Dec-数数的梦】数位dp


下一篇:Pycharm 报错 AttributeError: module 'pip' has no attribute 'main'