html - socket.io 更新所有打开的页面
问题描述
我正在尝试创建一个聊天网站,类似于不和谐的克隆。我正在使用 socket.io 连接我的前端和后端,但我不知道如何使它在有人输入消息时显示在所有当前打开的浏览器页面上
Server.js(我使用的服务器文件):
const express = require("express");
const app = express();
const http = require("http").Server(app);
const port = 4000;
const io = require("socket.io")(http);
app.get("/", (req, res) => {
res.sendFile("ChatRoom.html", {"root": __dirname});
});
io.on("connection", (socket) => {
console.log("A user has connected");
socket.on("messageSend", (data) =>{
console.log(data);
io.emit("chatUpdate", data);
});
});
http.listen(port, () => {
console.log("Server.js listening on port " + port );
});
还有我在 HTML 文件中的 Javascript 代码: var socket = io(); document.addEventListener('keydown', InputText);
function InputText(e)
{
//Checks if the pressed button is Enter and if the input box is empty
if( e.keyCode == 13 && document.getElementById("chat_input").value != "")
{
//Gets the div which the message will be ridden to
var parent = document.getElementById("chat");
//Current date to be used when displaying the exact time of sending the
messgae
let d = new Date()//.getTimezoneOffset();
//Getting the properties of the input
var value = document.getElementById("chat_input");
//Telling the server that a message has been sent - function
emitter(parent, value.value, d);
//Setting the text box back to blank
value.value = "";
}
}
//Function
function emitter(holder, text, date){
socket.emit("messageSend", text);
socket.once("chatUpdate", (message) => {
var z = document.createElement("p");
z.innerText = date.getHours() +":"+ date.getMinutes() + " | " +
message;
z.style = 'border-top: 1px solid Black;border-bottom: 1px solid
Black;font-size:20px; margin: 0;padding: 10px;';
holder.appendChild(z);
});
}
解决方案
发出消息后,您需要在客户端中监听它,如果您尝试实现的操作是将消息发送给当前在其窗口上打开套接字的另一个用户。因为您将它发送给用户而不是服务器,所以您需要连接到套接字,所以您的套接字很可能需要像这样定义。
var socket = io.connect('Your:/url/of/windowlocation/whileonsocket/here')
希望这可以帮助!
推荐阅读
- javascript - 给定当前日期,如何获得过去 24 个月的最后一天?
- jquery - 使用 jQuery 对 JSON 数据进行分页?
- payment-gateway - 在贝宝快递结帐中禁止/禁用运输选项
- pandas - 在熊猫数据框中用 nan 替换任何字符串
- r - R Shiny 需要很长时间来加载数据集,尽管不是那么大
- java - Javaw.exe 应用程序未打开,Windows 10 Pro Surface Pro 4
- python - FileNotFoundError:[WinError 3] - os.rename 不起作用
- scala - 如何一次通过多个谓词过滤列表?
- r - SMOTE 如何从分类数据创建新数据?
- mongodb - 没有 MongoSpark 无法从 Spark 向 MongoDB 插入数据