python tornado-websocket.py

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python tornado-websocket.py相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import tornado.escape
import gzip, StringIO

from tornado.options import define, options
define("port", default=13004, help="run on the given port", type=int)
define("debug", default=True, help="run on the given port", type=bool)
define("decompress_request", default=True, help="run on the given port", type=bool)


live_clients = set()

def send_message_by_websocket(message):
    removable = set()
    for ws in live_clients:
        if not ws.ws_connection or not ws.ws_connection.stream.socket:
            removable.add(ws)
        else:
            ws.write_message(message)

    for ws in removable:
        live_clients.remove(ws) 

def uncompressed_gzip_from_binary(body):
    """ 从字符串读取 gzip 并解压返回可读字符串 """
    fake_file = StringIO.StringIO(body)
    uncompressed = gzip.GzipFile(fileobj=fake_file, mode='rb')
    return uncompressed.read()


class TerminalHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('terminal.html', ws_address='ws://10.115.70.106:13004/ws')


class HeadOffHandler(tornado.web.RequestHandler):
    def post(self):
        data = self.request.body 
        #message = uncompressed_gzip_from_binary(data)
        send_message_by_websocket(data)
        print(data)
        return self.write('ok')

class SocketLogHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print("WebSocket opened")
        self.set_nodelay(True)
        live_clients.add(self)

    def on_message(self, message):
        self.write_message(u"You said: " + message)

    def on_close(self):
        print("WebSocket closed")

if __name__ == '__main__':
   tornado.options.parse_command_line()
   app = tornado.web.Application(handlers=[
        (r'/terminal', TerminalHandler),
        (r"/api/log/", HeadOffHandler),
        (r'/ws', SocketLogHandler),
    ])
   http_server = tornado.httpserver.HTTPServer(app, decompress_request=True)
   http_server.listen(options.port)
   tornado.ioloop.IOLoop.instance().start() 

以上是关于python tornado-websocket.py的主要内容,如果未能解决你的问题,请参考以下文章

代写python,代写python编程,python代写,python编程代写,留学生python代写

001--python全栈--基础知识--python安装

Python代写,Python作业代写,代写Python,代做Python

Python开发

Python,python,python

Python 介绍