python-socketio与flask-socketio的命名空间实现

服务器端使用flask-socketio,客户端使用python-socketio。

服务器端使用flask-socketio的命名空间以区分不同类型的客户端

引入包

from flask_socketio import SocketIO, send, Namespace, emit
from flask import Flask, render_template, request
from flask_cors import CORS

Flask app初始化

app = Flask(__name__)
CORS(app, resources=r'/*')
app.secret_key = "secret"

使用socketio对app进行封装

socketio = SocketIO(app, ping_timeout=1000, ping_interval=5)

# :param ping_timeout: The time in seconds that the client waits for the
#                      server to respond before disconnecting. The default is
#                      60 seconds.
# :param ping_interval: The interval in seconds at which the client pings
#                       the server. The default is 25 seconds.

ping_timeout、ping_interval用于socketio的保活。

ping_timeout指客户端在等待若干秒后就算超时。

ping_interval指客户端发送心跳包的间隔。

命名空间的定义

sid_list = ['']


class ClientA(Namespace):

    def on_connect(self):
        print('ClientA connected')
        print('request.sid', request.sid)
        sid_list[0] = request.sid

    def on_disconnect(self):
        print('ClientA disconnected')

    def on_client_name(self, data):
        emit('rece_msg', {'msg': 'hello ' + data['client_name']},
             namespace='/ClientA')

    def on_send_msg(self, data):
        print('client says: ', data)

    try:
        @classmethod
        def send_msg(cls, data):
            print(data)
            emit('method', {'content': data},
                 to=sid_list[0],
                 namespace='/ClientA')

    except Exception as e:
        print(e)

注册命名空间:

#注册命名空间类
socketio.on_namespace(ClientA('/ClientA'))

服务器启动:

if __name__ == '__main__':
    try:
        socketio.run(app, host='localhost', port=5001)
    except Exception as e:
        print(e)

客户端使用python-socketio:

import socketio

sio = socketio.Client()


class ClientA(socketio.ClientNamespace):

    def send_client_name(self):
        print('sending msg to server')
        # 获取用户名
        name = input("Input your name: ")

        sio.emit('client_name', {'client_name': name}, namespace='/ClientA')

    def send_msg(self):
        while True:
            msg = input("Input your msg: ")
            sio.emit('msg', {'msg': msg}, namespace='/ClientA')

    def on_connect(self):
        print('connection established')
        self.send_client_name()
        self.send_msg()

    def on_disconnect(self):
        print('disconnected from server')

    def on_rece_msg(self, data):
        print('server says: ', data)


# connect to server
try:
    sio.register_namespace(ClientA('/ClientA'))
    sio.connect('http://localhost:5001')
except Exception as e:
    print(e)
    exit()

命名空间响应方式举例:

客户端向服务器端发送:

sio.emit('client_name', {'client_name': name}, namespace='/ClientA')

该行代码的意思是,

sio.emit('事件名称', json格式消息, namespace='/命名空间名称')

服务器端响应'client_name'事件的函数即为:

def on_client_name(self, data):
    emit('rece_msg', {'msg': 'hello ' + data['client_name']},
         namespace='/ClientA')

以上代码的意思是:

def on_事件名称(self, json消息):
    emit('另一个事件名称', {'另一个json键': 'hello ' + json消息['json键']},
         namespace='/命名空间名称')

并注意:

本文flask-socketio发送消息使用的emit方法来自:

from flask_socketio import emit

本文python-socketio发送消息使用sio.emit方法来自:

import socketio

sio = socketio.Client()

···

sio.emit('client_name', {'client_name': name}, namespace='/ClientA')

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值