django渠道hadling连接

oymdgrw7  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(107)

我在Django频道上遇到了麻烦,我猜是客户端的连接问题,但也许不是。我的代码看起来像这样:

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页面?

u7up0aaq

u7up0aaq1#

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

async def connect(self):
    self.room_group_name = f"external_{self.scope['user'].id}"
    
    if self.room_group_name in self.active_connections:
        await self.close()
    else:
        self.active_connections[self.room_group_name] = self.channel_name
        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()

相关问题