【问题标题】:socket.io Updating all the open pagessocket.io 更新所有打开的页面
【发布时间】:2019-01-13 20:15:58
【问题描述】:

我正在尝试创建一个聊天网站,类似于 discord 克隆。我正在使用 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);

   });
   }

【问题讨论】:

    标签: html css node.js express socket.io


    【解决方案1】:

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

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

    希望这会有所帮助!

    【讨论】:

    • 在我的代码中定义为var socket = io.connect("http://localhost:4000");@Ashton Hauser
    • 你是否也监听过客户端的套接字发射?
    • 我设法解决了这个问题,我的客户端仅在调用 InputText 函数时才检查消息,但我必须一直检查更新,但现在我遇到了第一个消息的问题不会在所有客户端页面上弹出
    猜你喜欢
    • 2014-01-03
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 2021-06-26
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多