flask-Sockets 配合gevent-websocket实现flask框架

本文介绍了一种使用WebSocket和Flask框架实现双向实时通信的方法。通过创建WebSocketApplication子类和使用Flask-Sockets插件,可以实现实时消息推送和心跳检测等功能,适用于构建实时聊天、在线协作等应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

服务端

from geventwebsocket import WebSocketApplication
from flask_sockets import Sockets
from flask import Flask, Blueprint

sockets = Sockets(app)
ws = Blueprint(r'ws', __name__)
sockets.register_blueprint(ws, url_prefix=r'/')
app = Flask(__name__)


class EchoApplication(WebSocketApplication):

    def on_open(self):
        LOGGER.info(u'有人连接啦')
        self.ws.send(u'connection success')

    def on_message(self, message):
        try:
            if isinstance(message, dict):
                message = json.dumps(message)
            LOGGER.info(u'接收数据:%s' % (message))
            message = json.loads(message)
            msg_type = message["type"]
        except:
            self.send_error('unknow message!')
            return

        # sid = request.sid

        # return
        if msg_type == 'heart_msg':
            self.handle_online_device(message)
            return
        if msg_type == 'authentication':          
                self.ws.send(json.dumps({}))
            else:
                self.send_error(u'身份认证失败', operation=u'authentication')
                self.ws.close()
            return

    def on_close(self, reason):
        print(u'有人断开了,hhhhhhh')

if __name__ == "__main__":
    from werkzeug.debug import DebuggedApplication
    from app.websocket.websocket import EchoApplication
    from geventwebsocket import Resource, WebSocketServer
    WebSocketServer(('0.0.0.0', 8084),
                    Resource([('/', EchoApplication), ('^/.*', DebuggedApplication(app))]), debug=False).serve_forever()

客户端

from websocket import create_connection
ws = create_connection("ws://localhost:5000/echo")
ws.send("Hello, linyk3")
result = ws.recv()
print(result)
ws.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冰码达

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值