最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - socket.io not sending to client - Stack Overflow

programmeradmin2浏览0评论

I am trying to create a simple script to send data from a file every to the client every time the file is updated. I have tested and found that the file is read, but the client doesn't receive anything. there are no errors in the console. I am fairly new to socket.io.

node.js code

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require("fs");
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
    res.sendFile(__dirname + '/popup.html');
});

fs.watchFile("assets/popup.json", {interval:100}, function(curr, prev)
{
    fs.readFile("assets/popup.json",{encoding:"utf8"}, function(err, data){
        io.emit("popup", data)
    })
});
http.listen(port, function(){
    console.log('listening on *:' + port);
});

client code

var socket = io();
socket.on('popup', function(msg){
    alert("hello")
});

I am trying to create a simple script to send data from a file every to the client every time the file is updated. I have tested and found that the file is read, but the client doesn't receive anything. there are no errors in the console. I am fairly new to socket.io.

node.js code

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require("fs");
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
    res.sendFile(__dirname + '/popup.html');
});

fs.watchFile("assets/popup.json", {interval:100}, function(curr, prev)
{
    fs.readFile("assets/popup.json",{encoding:"utf8"}, function(err, data){
        io.emit("popup", data)
    })
});
http.listen(port, function(){
    console.log('listening on *:' + port);
});

client code

var socket = io();
socket.on('popup', function(msg){
    alert("hello")
});
Share Improve this question edited Aug 22, 2017 at 2:10 Tyler Silva asked Aug 22, 2017 at 1:08 Tyler SilvaTyler Silva 4217 silver badges14 bronze badges 6
  • Are you 100% sure that you are getting to the io.emit(). If you put a console.log() statement there, do you see that statement in the console? – jfriend00 Commented Aug 22, 2017 at 2:00
  • yes, i had console.log(data), and it printed out the data, and didn't receive anything on the page – Tyler Silva Commented Aug 22, 2017 at 2:01
  • Then please show us all relevant code that initializes your socket.io server. Also, you can put io.on('connect', ...) in the client with a console.log() in the callback to see if the client thinks it is connecting. And, you can register various listeners for connect errors in the client to see if any of those are getting hit. When in doubt with event driven programming, register all possible error handlers to see if any are getting triggered. – jfriend00 Commented Aug 22, 2017 at 2:02
  • updated with all of my nodejs code, a lot of it is sample code from the socket.io website – Tyler Silva Commented Aug 22, 2017 at 2:11
  • What is the URL in the browser bar that the client code is loaded in because that's the host and port that io() will attempt to connect to. I still think you need to install all possible error message handlers on the client side io object to see what they report. And, install the connect message handler to see if it gets hit. – jfriend00 Commented Aug 22, 2017 at 2:22
 |  Show 1 more ment

3 Answers 3

Reset to default 5

Whenever things aren't working right like this, you need to resort to "debug mode". In that mode, you need to gather all possible events that might be happening and see what you learn from that. To that end, add this code to the client:

var socket = io();
socket.on('popup', function(msg){
    console.log("hello: ", msg)
});
socket.on('connection', function() {
    console.log("client connected");
});

socket.on('connect_error', function(err) {
    console.log("client connect_error: ", err);
});

socket.on('connect_timeout', function(err) {
    console.log("client connect_timeout: ", err);
});

These messages are all documented in the client-side doc on the socket.io Github site which you can find by Googling "socket.io github" at any time.

Then, see what you see in the browser console when the page loads. If you don't know how to open the browser console in whichever browser you are using, google it to find out. You need to be looking at the debug console when the page loads.

FYI, we're assuming that you've loaded socket.io into the page via a script tag before this code. If not, that error will show in the console too.


The OP then gets this error:

client connect_error: 
    Error: server error at Socket.onPacket (socket.io-1.2.0.js:1) 
      at XHR.<anonymous> (socket.io-1.2.0.js:1) 
      at XHR.Emitter.emit (socket.io-1.2.0.js:1) 
      at XHR.Transport.onPacket (socket.io-1.2.0.js:1) 
      at callback (socket.io-1.2.0.js:2) 
      at Object.exports.decodePayload (socket.io-1.2.0.js:2) 
      at XHR.Polling.onData (socket.io-1.2.0.js:2) 
      at Request.<anonymous> (socket.io-1.2.0.js:2) 
      at Request.Emitter.emit (socket.io-1.2.0.js:1) 
      at Request.onData (socket.io-1.2.0.js:2)

OK, progress. How are you loading socket.io in the client page? This seems like it might be that you have mismatched versions of socket.io in client and server. You should be doing:

<script src="/socket.io/socket.io.js"></script>

and then your server will be feeding the client page the exact same version of socket.io. Also, since this error reports client-side socket.io 1.2.0, what version of socket.io is installed on the server?

try this

    socket.on('popup', function(msg){
         socket.emit('message',"popup");
    });

The issue appears to be you don't actually connect to a local socket.io server. By running node server.js with the code below you can start a web server. Then navigate to localhost in your browser to see the changes in console made to popup.json.

server.js

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

app.listen(80);

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

fs.watchFile("popup.json", {interval: 100}, function (curr, prev) {
    fs.readFile("popup.json", {encoding: "utf8"}, function (err, data) {
        io.emit("popup", JSON.parse(data));
    })
});

index.html

<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io('http://localhost');
    socket.on('popup', function (data) {
        console.log(data);
    });
</script>
发布评论

评论列表(0)

  1. 暂无评论