我正在处理在express.js和socket.io上运行的基本聊天应用程序。
服务器端代码:
var express = require("express");
var app = express();
var server = require('http').createServer(app);
var io = require("socket.io").listen(server);
var path = require("path");
app.use(express.static(path.join(__dirname, "public")));
app.set("view engine", "ejs");
server.listen(process.env.PORT || 3000, function() {
console.log("Server listening");
})
app.get("/", function(req, res) {
res.render("chat");
})
io.sockets.addListener("connection", function(socket) {
socket.addListener("chat-message", function(message, nickname) {
io.sockets.emit("chat-message", message, nickname)
})
})
客户端代码:
var socket = io();
var nickname = prompt("Whats your name?");
var input = document.getElementById("text-input");
var container = document.getElementById("chat-container");
input.addEventListener("keydown", function() {
if (event.keyCode == 13) {
event.preventDefault();
if (input.value !== "") {
socket.emit("chat-message", nickname + ": " + input.value);
input.value = "";
}
}
})
socket.addEventListener("chat-message", function(message) {
container.innerHTML += message + "</br>";
})
有什么办法可以避免在刷新后从网页上删除信息?
答案 0 :(得分:1)
您可以将全部消息和昵称保存在globar变量中,并在每个与套接字的新连接上发送它们。
var messages = [];
io.sockets.addListener("connection", function(socket) {
//send messages to new connection
socket.addListener("chat-message", function(message, nickname) {
messages.push({message: message, nickname: nickname});
io.sockets.emit("chat-message", message, nickname)
})
})
<强> [编辑] 强>
客户端
socket.addEventListener("chat-previous-messages", function(messages) {
for(let i = 0; i < messages.length; i++){
container.innerHTML += messages[i].message + "</br>";
}
})
服务器端
var messages = [];
io.sockets.addListener("connection", function(socket) {
socket.emit('chat-previous-messages', messages); //new code
socket.addListener("chat-message", function(message, nickname) {
messages.push({message: message, nickname: nickname});
io.sockets.emit("chat-message", message, nickname)
})
})
或者您可以使用已显示的消息提供聊天页面
app.get("/", function(req, res) {
res.render("chat", messages);
})
//in the html part something like this
#chat-container
- each message in messages
message.message + '<br>'