首页 > 解决方案 > 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);

   });
   }

标签: htmlcssnode.jsexpresssocket.io

解决方案


发出消息后,您需要在客户端中监听它,如果您尝试实现的操作是将消息发送给当前在其窗口上打开套接字的另一个用户。因为您将它发送给用户而不是服务器,所以您需要连接到套接字,所以您的套接字很可能需要像这样定义。

var socket = io.connect('Your:/url/of/windowlocation/whileonsocket/here')

希望这可以帮助!


推荐阅读