简体   繁体   中英

nodejs and socketio -Cannot send messages

I wanted to create a chat-like application so started using nodejs and socket.io. For simplicity (Firstly, I wanted to understand how it works), I made a button to emit message to the server which in turn should (in my novice understanding) change the content of the paragraph of all the web-pages currently pointing to that URL. My problem is, the content of webpage from which I emit the message gets changed but happens nothing to the same paragraph of other webpages pointing to same URL.

Here is my code:

// 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);
      });
});

The following is my HTML( client-side) file( ONLY THE RELEVANT SECTIONS):

<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: I opened two localhost:8080 on my google-chrome and clicked on the CHECKBUTTON of one of those.

What I expected : Paragraph with id=my_messages in both tab(localhost:8080) to change to the data- "Something has changed"

What actually happened: paragraph from where I clicked the button changed to desired string. It proved that the message went to the server and it was the server's emitted response that triggered the event in the page to change the paragraph. But nothing happened to the other (localhost:8080).

What am I missing? Am I fundamentally thinking in a wrong direction here?

change 1 line in server.js

// from

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

// to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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