繁体   English   中英

nodejs和socketio-无法发送消息

[英]nodejs and socketio -Cannot send messages

我想创建一个类似聊天的应用程序,因此开始使用nodejs和socket.io。 为简单起见(首先,我想了解它的工作原理),我制作了一个向服务器发送消息的按钮,该按钮应(以我的新手理解)应更改当前指向该页面的所有网页的内容。网址。 我的问题是,发出消息的网页的内容发生了变化,但指向相同URL的其他网页的同一段却什么也没有发生。

这是我的代码:

// This is server.js


var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs');

app.listen(8080);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
  socket.on('user_event', function (data) {
        socket.emit("to_all_users","something has changed");
        console.log(data);
      });
});

以下是我的HTML(客户端)文件(仅相关部分):

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');

  socket.on('to_all_users', function (data) {
      var msgs=document.getElementById("my_messages");
      msgs.innerHTML=data;  
      });

  function send_to_server(){
      socket.emit("user_event","Here is the new news");
  }
</script>

</head>
<body>
<button onclick="send_to_server()">CHECKBUTTON</button>
<p id="my_messages">Here is the messages</p>

What I did:我在Google-chrome上打开了两个localhost:8080,然后单击其中之一的CHECKBUTTON。

What I expected :两个选项卡(localhost:8080)中的id = my_messages的段落都将更改为数据-“事情已更改”

What actually happened:单击按钮的段落更改为所需的字符串。 事实证明消息已到达服务器,并且是服务器发出的响应触发了页面中的事件以更改段落。 但是其他都没有发生任何变化(localhost:8080)。

我想念什么? 我在这里从根本上想错了方向吗?

更改server.js中的1行

//来自

socket.emit("to_all_users","something has changed");

// 至

io.sockets.emit("to_all_users", "something has changed");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM