Application of WebSocket in flask and tornado

Source: Internet
Author: User
Tags sendmsg

A. Installation
    pip3 install gevent-websocket         作用:        - 处理Http、Websocket协议的请求 -> socket         - 封装Http、Websocket相关数据   -> request
B. Basic structure
    from geventwebsocket.handler import WebSocketHandler    from gevent.pywsgi import WSGIServer            @app.route('/test')    def test():        ws = request.environ.get('wsgi.websocket')        ws.receive()        ws.send(message)        ws.close()        return render_template('index.html')                        if __name__ == '__main__':        http_server = WSGIServer(('0.0.0.0', 5000,), app, handler_class=WebSocketHandler)        http_server.serve_forever()
C. Web chat Room:
    Backend: From Geventwebsocket.handler import websockethandler from Gevent.pywsgi import Wsgiserver fro M flask import flask,render_template,request import Pickle app = Flask (__name__) App.secret_key = ' XF         Sdfqw ' @app. Route ('/index ') def index (): Return render_template (' index.html ') ws_list = []                 @app. Route ('/test ') def Test (): WS = Request.environ.get (' wsgi.websocket ') if not WS:                Return ' Please use WebSocket protocol ' # WebSocket connection has succeeded Ws_list.append (WS) while True:  # waits for the user to send a message, and accepts MSG = Ws.receive () # Close: Message=none if not                    Message:WS_LIST.remove (WS) break for item in Ws_list: Item.Send (message) return "..." if __name__ = = ' __main__ ': http_server = Wsgiserver (' 0 .0.0.0 ',,,), app, haNdler_class=websockethandler) Http_server.serve_forever () Front End: <! DOCTYPE html> 
D. tornado.websocket Example
            Import tornado from Tornado.web import application from Tornado.web import RequestHandle                R from tornado.websocket import Websockethandler class Indexhandler (RequestHandler): def get (self, *args, **kwargs): # self.write (' Hello World ') self.render (' index.html ') ) def post (self, *args, **kwargs): User = self.get_argument (' user ') s Elf.write (' success ') ws_list = [] class MessageHandler (Websockethandler): Def open (self, *                    args, **kwargs): Ws_list.append (self) def on_message (self, message):                    For WS in WS_LIST:ws.write_message (message) def on_close (self): Ws_list.remove (self) settings = {' Template_path ': ' Templates ', ' Static_path ': ' STA      Tic ',}      App = Application ([r "/index", Indexhandler), (R "/message", MessageHandler),                ],**settings) If __name__ = = ' __main__ ': App.listen (address= ' 0.0.0.0 ', port=9999) Tornado.ioloop.IOLoop.instance (). Start ()

WebSocket applications in flasks and tornadoes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.