django 通道处理连接

问题描述 投票:0回答:1

我在使用 django 通道时遇到了麻烦,我猜它与客户端上的 hadling 连接有关,但也许不是。所以我的代码如下所示:

class ExternalDataConsumer(AsyncWebsocketConsumer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.active_connections = {}

    async def connect(self):
        self.room_group_name = f"external_{self.scope['user'].id}"  # Match the group name from the signal
        await self.channel_layer.group_add(self.room_group_name, self.channel_name)
        logger.info(f"Connected to group: {self.room_group_name}")
        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(self.room_group_name, self.channel_name)

    async def receive(self, text_data):
        try:
            data = json.loads(text_data["text_data"])
            if data:
               asyncio.ensure_future(await self.start_external_stream(data))
            else:
               asyncio.ensure_future(await self.stop_extenal_stream(data))
            # start or stop external stream

        except Exception as e:
            logger.error(f"ERROR receiving websocket: {e}")

   async def start_external_stream(self, data):
      # do something with data, send payload and get data from stream
   async def stop_external_stream(self, data):
      # stop existing steam for data
   async def send_notification(self, data):
      # sending notification to user

所以问题是当我开始从外部流获取数据时,每次用户重新加载页面时数据都会翻倍。在客户端上,我就像从 django 通道 websocket 获取数据一样:

 if (isWebSocketConnected === 'true') {
    socket = new WebSocket('ws://0.0.0.0:8000/ws/binance_consumer/');
} else {
    socket = new WebSocket('ws://0.0.0.0:8000/ws/binance_consumer/');
    localStorage.setItem('websocketConnected', 'true');
}

const notifications = [];

// Handle WebSocket events
socket.addEventListener("open", (event) => {
    console.log("WebSocket connected");
});

socket.addEventListener("message", (event) => {
    const data = JSON.parse(event.data);
    // Extract the message and timestamp from the received data
    const message = data.message;
    const timestamp = data.timestamp;

    // Add the message to the notifications array along with the timestamp
    notifications.push({ message, timestamp });

    // If the number of notifications exceeds the maximum, remove the oldest ones
    if (notifications.length > maxNotifications) {
        notifications.shift(); // Remove the oldest notification
    }

    // Update the UI to display the notifications
    updateNotificationsUI();
});

这个逻辑我会错过什么,所以每个用户的数据每次在他的 realod 页面时不会加倍?

javascript python django django-channels
1个回答
0
投票

所以,我想我解决了这个问题,只需检查订阅是否退出

© www.soinside.com 2019 - 2024. All rights reserved.