简体   繁体   English

socket.io没有发送给客户端

[英]socket.io not sending to client

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. 我对socket.io相当陌生。

node.js code node.js代码

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

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. 这些消息全部记录在socket.io Github站点上的客户端文档中,您可以随时通过谷歌搜索“ socket.io github”来找到它们。

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. 如果您不知道如何在使用的浏览器中打开浏览器控制台,请在Google上进行查找。 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. 仅供参考,我们假设您已在此代码之前通过脚本标记将socket.io加载到页面中。 If not, that error will show in the console too. 如果不是,该错误也将显示在控制台中。


The OP then gets this error: 然后,OP收到此错误:

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? 您如何在客户端页面中加载socket.io? This seems like it might be that you have mismatched versions of socket.io in client and server. 似乎您在客户端和服务器中的socket.io版本不匹配。 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. 然后您的服务器将向客户端页面提供完全相同版本的socket.io。 Also, since this error reports client-side socket.io 1.2.0, what version of socket.io is installed on the server? 另外,由于此错误报告了客户端socket.io 1.2.0,因此服务器上安装了哪个版本的socket.io?

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. 问题似乎是您实际上没有连接到本地socket.io服务器。 By running node server.js with the code below you can start a web server. 通过使用下面的代码运行node server.js,可以启动Web服务器。 Then navigate to localhost in your browser to see the changes in console made to popup.json. 然后在浏览器中导航到localhost,以查看控制台中对popup.json所做的更改。

server.js 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 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>

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

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