You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django Channels中group_send()无法推送消息的问题求助

Django Channels group_send() 消息无法被其他客户端接收问题

我正在使用Django Channels开发,已成功建立WebSocket连接,但调用group_send()发送的消息无法被其他客户端接收。以下是相关代码及信息:

消费者代码

class EchoConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()
        logger.info(f" echo echo..  ")

        self.channel_layer.group_add("ks", self.channel_name)

    async def disconnect(self, close_code):
        self.channel_layer.group_discard("ks", self.channel_name)
        logger.info(f"ti ti tiiin")

        self.close()

    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json["message"]
        logger.info(message)

        await self.channel_layer.group_send(
            "ks",
            {
                "type": "group.message",
                "message": message,
            },
        )

    async def group_message(self, event):
        logger.info(event["message"])
        message = event["message"]

        await self.send(text_data=json.dumps({"message": message}))

通道层配置

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": ["redis://" + REDIS_HOST + ":" + REDIS_PORT + "/1"],
        },
    },
}
# chaches
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": f"redis://{REDIS_HOST}:{REDIS_PORT}/3",  # Use a different database (e.g., 1)
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        },
    },
}

通道层测试结果

(env) komal@phoenix:~/Documents/gle/server$ python manage.py shell
Python 3.11.4 (main, Dec  7 2023, 15:43:41) [GCC 12.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from channels.layers import get_channel_layer
>>> channel_layer = get_channel_layer()
>>> channel_layer.group_send("ks" , {"message":"I am working"})
<coroutine object RedisChannelLayer.group_send at 0x7fb2b0167ca0>
>>> 

运行日志

WebSocket HANDSHAKING /ws/echo/ [127.0.0.1:38026]
WebSocket HANDSHAKING /ws/echo/ [127.0.0.1:38026]
WebSocket CONNECT /ws/echo/ [127.0.0.1:38026]
WebSocket CONNECT /ws/echo/ [127.0.0.1:38026]
 echo echo..  
WebSocket HANDSHAKING /ws/echo/ [127.0.0.1:38032]
WebSocket HANDSHAKING /ws/echo/ [127.0.0.1:38032]
WebSocket CONNECT /ws/echo/ [127.0.0.1:38032]
WebSocket CONNECT /ws/echo/ [127.0.0.1:38032]
 echo echo..  
hello

客户端代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>WebSocket Chat</title>
    <style>
      /* Add your CSS styles here */
    </style>
  </head>
  <body>
    <div id="chat">
      <!-- Chat messages will be displayed here -->
    </div>
    <input type="text" id="messageInput" placeholder="Type a message..." />
    <button id="sendButton">Send</button>

    <script>
      const socket = new WebSocket("ws://localhost:8000/ws/echo/");

      socket.onopen = () => {
        console.log("WebSocket connection established.");
      };

      socket.onmessage = (event) => {
        const message = JSON.parse(event.data).message;
        appendMessageToChat(message);
      };

      socket.onclose = () => {
        console.log("WebSocket connection closed.");
      };

      document.getElementById("sendButton").addEventListener("click", () => {
        const messageInput = document.getElementById("messageInput");
        const message = messageInput.value.trim();
        if (message !== "") {
          socket.send(JSON.stringify({ message }));
          messageInput.value = ""; // Clear input field after sending
        }
      });

      function appendMessageToChat(message) {
        const chat = document.getElementById("chat");
        const messageElement = document.createElement("div");
        messageElement.textContent = message;
        chat.appendChild(messageElement);
      }
    </script>
  </body>
</html>

经检查通道层无异常,但其他客户端始终无法收到消息,尝试多种方案未解决,寻求技术帮助。

内容的提问来源于stack exchange,提问作者komal sai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 00:44:54