admin
2024-01-11 a674a57120c3530151aa7b79d843a84ffb703e1d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
推送消息管理器
"""
import json
 
from log import logger_debug
from utils import socket_util
 
TYPE_ORDER_ALMOST_DEAL = "order_almost_deal"  # 订单即将成交
 
TYPE_DELEGATE_QUEUE_CHANGE = "delegate_queue_change"  # 委托队列变化
 
 
# 格式:{id:(sk,[type1,type2])}
 
class SocketManager:
    __sockets_dict = {}
 
    # 注册socket
    @classmethod
    def regirster_socket(cls, sk, types: list):
        if sk is None:
            return
        _id = id(sk)
        cls.__sockets_dict[_id] = (sk, types)
 
    @classmethod
    def get_sockets(cls, _type):
        sockets = []
        for k in cls.__sockets_dict:
            if _type in cls.__sockets_dict[k][1]:
                sockets.append(cls.__sockets_dict[k][0])
        return sockets
 
    @classmethod
    def remove_socket(cls, sk):
        _id = id(sk)
        if _id in cls.__sockets_dict:
            cls.__sockets_dict.pop(_id)
 
 
# 添加消息
def __push_msg(msg_type, data=None):
    fdata = {"type": msg_type}
    if data:
        fdata["data"] = data
    sks = SocketManager.get_sockets(msg_type)
    logger_debug.info(f"socket对象数量({msg_type}):{len(sks)}")
    if sks:
        for sk in sks:
            try:
                sk.sendall(socket_util.load_header(json.dumps({"code": 0, "data": fdata}).encode("utf-8")))
            except Exception as e:
                logger_debug.exception(e)
                try:
                    sk.close()
                except:
                    pass
                finally:
                    SocketManager.remove_socket(sk)