【发布时间】:2019-07-26 03:37:56
【问题描述】:
我正在构建一个基本的聊天程序(来自 CS50s 网络编程的 Flack)。
我有一本字典,其中我将频道和消息存储为键值对。
消息在一个列表中,所以一个键值对看起来像:
{"channelExample" : ["msg1", "msg2"]}。
我还有另一个变量,用于跟踪用户正在发送消息的当前房间/频道,称为 currentRoom。
当用户提交消息时,我正在尝试通过执行以下操作来更新该频道中的消息(emit 已导入并且我已确认 currentRoom & 输入消息是字符串值):
@socketio.on("submit message")
def submitMessage(message):
channels[currentRoom].append(message)
emit("display message", message)
但是,channels[currentRoom].append(message) 出现“线程中的异常...”错误,我不知道为什么。
我在 Flask 中的完整代码:
import os
from flask import Flask, session, render_template, url_for, request, flash, redirect, jsonify
from flask_socketio import SocketIO, send, emit, join_room, leave_room
app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
socketio = SocketIO(app)
currentRoom = None
channels = {}
@app.route("/")
def index():
return render_template("welcome.html", channels=channels)
@socketio.on("new channel")
def newChannel(channelName):
# Store new channel to keep track of it
channels.update( {channelName : []} )
@socketio.on("retrieve channels")
def retrieveChannels():
channelNames = []
for channel in channels:
channelNames.append(channel)
emit("providing channels", channelNames)
@socketio.on("retrieve messages")
def loadMessages(channelName):
currentRoom = channelName
channelMessages = channels[currentRoom]
emit("load messages", channelMessages)
@socketio.on("submit message")
def submitMessage(message):
channels[currentRoom].append(message)
emit("display message", message)
Javascript:
document.addEventListener('DOMContentLoaded', () => {
// Connect to websocket
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
// When connected,
socket.on('connect', () => {
var nameInput = document.querySelector("#usernameInput");
var welcomeMessage = document.querySelector("#welcomeMessage");
var createChannel = document.querySelector("#createChannel");
var newChannelForm = document.querySelector("#newChannelForm");
var newMessageForm = document.querySelector("#newMessageForm");
function userExists() {
// Check if user has come here before
if (localStorage.getItem("username")) {
// Display a welcome message
welcomeMessage.innerHTML = `Welcome back ${localStorage.getItem("username")}!`;
nameInput.style.display = "none";
return true;
}
else {
return false;
}
};
function createChannelBtn(name) {
// Create new channel & style it
let newChannel = document.createElement("button");
newChannel.id = name;
newChannel.innerHTML = name;
newChannel.className = "btn btn-block btn-outline-dark";
newChannel.style.display = "block";
// Attach to current list
document.querySelector("#channels").appendChild(newChannel);
// When someone clicks the channel
newChannel.onclick = () => {
newChannel.classList.toggle("active");
socket.emit("retrieve messages", newChannel.id);
console.log("Retrieving messages!!!");
socket.on("load messages", channelMessages => {
console.log("loading messages!");
for (let i = 0; i < channelMessages.length; i++) {
createMessage(channelMessages[i]);
}
});
};
};
function createMessage(messageContent) {
let message = document.createElement("h6");
message.innerHTML = messageContent;
document.querySelector("#messageWindow").appendChild(message);
console.log("Currently creating message!");
};
function loadChannels() {
socket.emit("retrieve channels")
socket.on("providing channels", channelNames => {
for (let i = 0; i < channelNames.length; i++) {
createChannelBtn(channelNames[i]);
}
});
};
// Make sure the new channel form is not displayed until "Create channel" button is clicked
newChannelForm.style.display = "none";
// Check if user exists already in local storage
userExists();
loadChannels();
// If someone submits a username...
nameInput.addEventListener("click", () => {
// if that username exists, do nothing
if (userExists()) {
}
// else remember the username
else {
localStorage.setItem("username", document.querySelector("#user").value);
}
});
// When someone wants to create a channel
createChannel.addEventListener("click", () => {
// Show form
newChannelForm.style.display = "block";
// When user inputs new channel name...
newChannelForm.onsubmit = () => {
// Retrieve their input
var newChannelName = document.querySelector("#newChannel").value;
// Create a new channel
createChannelBtn(newChannelName);
// Notify server to store new channel
socket.emit("new channel", newChannelName);
// Clear input field
document.querySelector("#newChannel").innerHTML = "";
return false;
};
});
newMessageForm.onsubmit = () => {
let message = document.querySelector("#newMessage").value;
console.log("You have entered " + message);
socket.emit("submit message", message);
console.log("Submitted message!");
socket.on("display message", message => {
createMessage(message);
console.log("Displaying message!!");
});
return false;
};
});
// DOM Ending Bracket
});
【问题讨论】:
-
你没有提供
welcome.html,调试起来很麻烦……
标签: javascript python flask socket.io flask-socketio