我刚刚完成了频道教程,并花了将近一周的时间编写用于上传静态文件的代码。您能帮我写js和Consumer.py吗?预先谢谢你。
我特别不明白:
我的代码是:
js
<script>
var obj = document.getElementById('talk_element');
obj.scrollTop = obj.scrollHeight;
var roomName = {{ room.pk }};
var chatSocket = new WebSocket(
'ws://' + window.location.host +
'/ws/room/' + roomName + '/');
chatSocket.onmessage = function(e) {
var data = JSON.parse(e.data);
var message = data['message'];
var file = data['file'];
var created_by = data['created_by']
var user = `{{ user }}`;
if (created_by == user) {
document.getElementById('talk_element').innerHTML += `
<li class="container card-text text-right text-black">
<span class="speech-bubble-user text-left">${message}</span>
<img src="${file}" max-width="350" height=auto/>
</li>`;
} else {
document.getElementById('talk_element').innerHTML += `
<li class="container card-text text-left text-black">
<span class="container speech-bubble text-left">${message}</span>
</li>`;
}
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13 && e.shiftKey) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
var messageInputDom = document.querySelector('#chat-message-input');
var message = messageInputDom.value;
var userInputDom = document.querySelector('#creat_by');
var user = userInputDom.value;
var fileInputDom = document.querySelector('#document');
var file = fileInputDom.value;
chatSocket.send(JSON.stringify({
'message': message,
'created_by':user,
}), file );
messageInputDom.value = '';
};
</script>
consumer.py
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_pk']
self.room_group_name = 'chat_%s' % self.room_name
# Join room group
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def disconnect(self, close_code):
# Leave room group
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
# Receive message from WebSocket
def receive(self, text_data=None):
self.user = self.scope["user"]
text_data_json = json.loads(text_data)
message = text_data_json['message']
created_by = text_data_json['created_by']
file = text_data_json['created_by']
room = Room.objects.get(pk=self.room_name)
talk = Talk.objects.create(
room=room,
message=message,
created_by=self.user,
date=timezone.now
)
# Send message to room group
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type': 'chat_message',
'message': message,
'created_by':created_by
}
)
# Receive message from room group
def chat_message(self, event):
message = event['message']
created_by = event['created_by']
# Send message to WebSocket
self.send(text_data=json.dumps({
'message': message,
'created_by':created_by
}))
答案 0 :(得分:0)
如果您希望JavaScript和Python都能正常通信,则需要运行WebSocket server。例如,您可以使用Tornado或使用this one构建一个。
一旦准备就绪,您需要在client side中做一些事情:
实例化WebSocket对象以建立连接
var exampleSocket = new WebSocket("wss://www.example.com/socketserver");
像这样将数据(作为字符串,Blob或ArrayBudder)发送到服务器
exampleSocket.onopen = function (event) {
exampleSocket.send("Here's some text that the server is urgently awaiting!");
};
如果要传输对象,请考虑使用JSON
function sendText() {
// Construct a msg object containing the data the server needs to process the message.
var msg = {
type: "message",
text: document.getElementById("text").value,
id: clientID,
date: Date.now()
};
// Send the msg object as a JSON-formatted string.
exampleSocket.send(JSON.stringify(msg));
}
从服务器接收消息
exampleSocket.onmessage = function (event) {
console.log(event.data);
}
如果您发送了JSON对象,则解释消息的代码可能如下所示:
exampleSocket.onmessage = function(event) {
var f = document.getElementById("chatbox").contentDocument;
var text = "";
var msg = JSON.parse(event.data);
var time = new Date(msg.date);
var timeStr = time.toLocaleTimeString();
switch(msg.type) {
case "id":
clientID = msg.id;
setUsername();
break;
case "username":
text = "<b>User <em>" + msg.name + "</em> signed in at " + timeStr + "</b><br>";
break;
case "message":
text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>";
break;
case "rejectusername":
text = "<b>Your username has been set to <em>" + msg.name + "</em> because the name you chose is in use.</b><br>"
break;
case "userlist":
var ul = "";
for (i=0; i < msg.users.length; i++) {
ul += msg.users[i] + "<br>";
}
document.getElementById("userlistbox").innerHTML = ul;
break;
}
if (text.length) {
f.write(text);
document.getElementById("chatbox").contentWindow.scrollByPages(1);
}
};
关闭连接
exampleSocket.close();