socket.io更新所有打开的页面

时间:2019-01-13 20:15:59

标签: html css node.js express 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);

   });
   }

1 个答案:

答案 0 :(得分:0)

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

Data.Proxy.Proxy

希望这会有所帮助!