Python 如何使用django通道和WebSocket从服务器的任何位置向客户端发送事件

Python 如何使用django通道和WebSocket从服务器的任何位置向客户端发送事件,python,django,websocket,django-channels,Python,Django,Websocket,Django Channels,现在我正在使用django和angular构建一个网站,我想在客户端和服务器之间添加websocket通信。 我遵循django频道文档的说明。() 我想从django服务器代码的任何地方发送任何事件。但当多个用户通过套接字进行连接时,从服务器发送的数据总是发送给最后一个连接的用户。 这就是我所做的。 首先在consumers.py中,我定义了ChatConsumer类,如下所示,并添加了一个名为“tweet\u send”函数的新处理程序 在django服务器端的某个地方(在serialize

现在我正在使用django和angular构建一个网站,我想在客户端和服务器之间添加websocket通信。 我遵循django频道文档的说明。() 我想从django服务器代码的任何地方发送任何事件。但当多个用户通过套接字进行连接时,从服务器发送的数据总是发送给最后一个连接的用户。 这就是我所做的。 首先在consumers.py中,我定义了ChatConsumer类,如下所示,并添加了一个名为“tweet\u send”函数的新处理程序

在django服务器端的某个地方(在serializers.py中),当创建一条新的tweet时,我使用django.channel\u层向所有用户发送一条新的tweet数据

...
def create(self, validated_data):
    ...
    new_tweet.save()

    # send message via channels
    channel_layer = get_channel_layer()
    all_users = list(Member.objects.filter(is_active = True).values_list('id', flat = True))
    for user_id in all_users:
        async_to_sync(channel_layer.group_send)(
            "chat_{}".format(user_id),            # this is the group name of group name of individual users.
            { "type": "chat_message", "message": "tweet created" }
        )
在角形websocket服务中

init(userID: number): void{
  if(this.ws){
    this.ws.close();
  }

  this.ws = new WebSocket(`${environment.WEBSOCKET_URL}/chat/${userID}/`);
  this.ws.onopen = () => {
    this.currentWebSocketSubject.subscribe(data => {
      if (data) {
        this.ws?.send(JSON.stringify(data));
      }
    });
  };

  this.ws.onmessage = (event) => {
    console.log("message arrived");
    console.log(event);
    if (event.data) {
      const tempData: WS = JSON.parse(event.data) as WS;
      switch (tempData.type) {
        case 'MESSAGE':
          console.log("message arrived");
          console.log(tempData);
          if (tempData.data) {
            this.unreadMessages++;
            this.messageSubject.next(tempData);
          }
          break;

      }
    }
  };
}
当我测试这些代码时,我使用了两个客户端,两个客户端登录,并通过WebSocket成功连接到django服务器。 当我创建一条tweet时,django服务器使用channel_layer.group_send函数向每个频道发送事件,在ChatConsumer类中,添加的“tweet_send”函数将事件发送给用户。 这些事件分别针对不同的用户。 但它们都被发送给连接websocket的用户。
我不知道为什么。请帮帮我。

我想您一定是在使用3.0.0频道,出现了此错误。我建议您将Channel版本升级到3.0.1或3.0.2。 然后错误就会消失

init(userID: number): void{
  if(this.ws){
    this.ws.close();
  }

  this.ws = new WebSocket(`${environment.WEBSOCKET_URL}/chat/${userID}/`);
  this.ws.onopen = () => {
    this.currentWebSocketSubject.subscribe(data => {
      if (data) {
        this.ws?.send(JSON.stringify(data));
      }
    });
  };

  this.ws.onmessage = (event) => {
    console.log("message arrived");
    console.log(event);
    if (event.data) {
      const tempData: WS = JSON.parse(event.data) as WS;
      switch (tempData.type) {
        case 'MESSAGE':
          console.log("message arrived");
          console.log(tempData);
          if (tempData.data) {
            this.unreadMessages++;
            this.messageSubject.next(tempData);
          }
          break;

      }
    }
  };
}