我正在尝试使用 Channels 在 Django 中创建群聊。在下面你可以看到我的代码。提交消息后没有任何反应。也登录为空。如何让代码工作?
路由.py:
channel_routing = [
route('websocket.connect', ws_connect, path=r'^account/dashboard/projects/(?P<project_code>[0-9a-f-]+)/chat/$'),
route("websocket.receive", ws_receive),
route("websocket.disconnect", ws_disconnect),
]
消费者.py:
# Connected to websocket.connect
@channel_session
def ws_connect(message):
query = parse.parse_qs(message['query_string'])
if 'username' not in query:
return
room = message.content['path'].strip("/")
Group('chat-%s' % room).add(message.reply_channel)
message.channel_session['room'] = room
message.channel_session['username'] = query['username'][0]
message.reply_channel.send({"accept": True})
# Connected to websocket.receive
@channel_session
def ws_receive(message):
if 'username' not in message.channel_session:
return
Group('chat-%s' % message.channel_session['room']).send({
'text': json.dumps({
'message': message.content['text'],
'username': message.channel_session['username']
})
})
# Connected to websocket.disconnect
@channel_session
def ws_disconnect(message):
Group("chat-%s" % message.channel_session['room']).discard(message.reply_channel)
模板:
{% block content %}
<h1>{{ room.code }}</h1>
<div id="msgArea"></div>
<div>
<textarea name="message" id="message" cols="30" rows="10"></textarea>
</div>
<button id="btnSubmit">Submit</button>
{% endblock content %}
{% block script %}
<script>
$(document).ready(function(){
var msgArea = $('#msgArea')
var elementMessage = $('#message')
var webSocket = new WebSocket('ws://' + window.location.host + '/account/dashboard/projects/(?P<{{ room.project_id }}>[0-9a-f-]+)/chat/');
webSocket.onmessage = function(message) {
var data = JSON.parse(message.data)
msgArea.append('<p><strong>'+ data.username + '</strong>: ' + data.message + '</p>')
}
$('#btnSubmit').click(function(e) {
webSocket.send(elementMessage.val())
})
})
</script>
{% endblock script %}