下面是部分代码,已做到客户端域服务器的收发,但是目前为止未找到服务器向客户端发送一条或者多条消息的实现方法,
需要实现的内容有,接受到一条消息后,可以实现向客户端发送一条或多条消息,或者只要客户端与服务器保持链接,就可以无限发送消息
想要实现上诉方式,该如何修改代码,或者需要什么模块
目前实现django websocket的方式是
channels ==3.0.4
from channels.generic.websocket import AsyncWebsocketConsumer
class MessagesConsumer(AsyncWebsocketConsumer):
async def connect(self):
#acceptlist.append(self)
#await self.accept()
await self.accept()
async def receive(self,text_data = None,bytes_data = None):
'''接收到后端发来的私信'''
import json
jsonobj = json.loads(text_data)
# for i in acceptlist:
# if i == self:
# if not acceptdict.get(jsonobj['id']):
# acceptdict[jsonobj['id']] = i
# await self.channel_layer.group_add(
# jsonobj['id'],
# self.channel_name
# )
if jsonobj['title'] == "port":
if jsonobj['option'] == "get":
jsonstr = getportname(jsonobj)
await self.send(text_data = jsonstr)
if jsonobj['option'] == "read":
jsonobj['data'] = "打开操作成功"
jsonstr = json.dumps(jsonobj)
await self.send(text_data = jsonstr)
async def disconnect(self,code):
'''离开聊天组'''
# await self.channel_layer.group_discard(self.scope['user'].username,self.channel_name)
# 关闭
await self.channel_layer.group_discard(self.scope,self.channel_name)
# await self.close()