我正在构建一个在线游戏,该游戏使用Django渠道2.1.5进行网络套接字。
我能够在客户端和服务器之间建立连接,并且也只能在使用者类内部发送数据:
from channels.generic.websocket import WebsocketConsumer
import json
from . import controller
class GameConsumer(WebsocketConsumer):
def connect(self):
self.accept()
print("Wohooo .. Connected to client!")
self.render()
controller.startTurn()
def render(self, type="render", message=None):
self.send(controller.renderMap(type, message))
def disconnect(self, close_code):
print("WebSocket connection is lost...")
def receive(self, text_data):
text_data_json = json.loads(text_data)
controller.handleRecieved(text_data)
...
现在,我想做的是从另一个模块中调用函数 render (位于消费者类中)
我尝试过:
from .. import consumer
def sendDeployments(owner, armies):
type = "renderDeployments"
message = owner + " has " + str(armies) + " to deploy"
dummyConsumer = consumer.GameConsumer()
consumer.GameConsumer.render(type, message)
但是失败了,因为我不能从类外部使用“ self”参数。
有人能想到实现我目标的方法吗?
Ps:我不在乎同步。
非常感谢。
答案 0 :(得分:2)
首先像
那样为您的消费者做出一些改变。from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
import json
class EventConsumer(WebsocketConsumer):
def connect(self):
# self.room_name = self.scope['url_route']['kwargs']['room_name']
# self.room_group_name = 'chat_%s' % self.room_name
self.room_name = 'event'
self.room_group_name = self.room_name+"_sharif"
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
print(self.room_group_name)
self.accept()
print("#######CONNECTED############")
def disconnect(self, code):
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
print("DISCONNECED CODE: ",code)
def receive(self, text_data=None, bytes_data=None):
print(" MESSAGE RECEIVED")
data = json.loads(text_data)
message = data['message']
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,{
"type": 'send_message_to_frontend',
"message": message
}
)
def send_message_to_frontend(self,event):
print("EVENT TRIGERED")
# Receive message from room group
message = event['message']
# Send message to WebSocket
self.send(text_data=json.dumps({
'message': message
}))
然后从您的应用程序的外部/任意位置调用函数,例如
def event_triger():
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
'event_sharif',
{
'type': 'send_message_to_frontend',
'message': "event_trigered_from_views"
}
)
# here 'event_sharif' is your room_group_name as i defined before in consumer
# 'type' is like a command, for which method you wants to trigger in your consumer
答案 1 :(得分:1)
首先,您需要您的使用者实例才能订阅组。
from asgiref.sync import async_to_sync
class GameConsumer(WebsocketConsumer):
def connect(self):
self.accept()
self.render()
async_to_sync(self.add_group)('render_updates_group')
controller.startTurn()
...
然后,如果您不在消费者之外,则需要向该组发送一条消息,以便所有注册到该组的消费者都可以收到该消息。
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
def sendDeployments(owner, armies):
type = "renderDeployments"
message = owner + " has " + str(armies) + " to deploy"
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
'render_updates_group',
{'type': 'render', 'message': message}
)
但是,您还需要记住在断开连接时将其从组中删除。
class GameConsumer(WebsocketConsumer):
....
def disconnect(self, close_code):
async_to_sync(self.group_name)('render_updates_group')
如果要限制哪些打开的连接会收到此渲染消息,则需要相应地建立组名。
例如,如果您正在考虑一些在线游戏,则可能在组名中包含MATCH-ID
,该组名由同一匹配的所有连接共享。
channels Layers documentation是一个很好的参考,但是请记住,在生产环境中运行此代码时,您需要设置一个消息传递层(通常为Redis)。
答案 2 :(得分:0)
断开连接功能的正确代码(使用2.3.0通道)应为:
class GameConsumer(WebsocketConsumer):
....
def disconnect(self, close_code):
self.channel_layer.group_discard(self.channel_name, 'render_updates_group')