javascript - Node.JS 服务器未发送数据(或客户端未接收)

标签 javascript node.js express socket.io

我有一个node.js服务器(使用socket.io和express)。我一切正常,但为了组织而将我的代码分成多个文件。

现在,客户端可以发送到服务器(并且服务器可以接收数据),但服务器不会将数据发送回客户端(客户端没有接收到发送的数据)。

这是我的服务器(app.js):

var variables = require('./variables');
var functions = require('./functions');
var connection = require('./connections');
var heartbeat = require('./heartbeat');

var mongoClient = require('mongodb').MongoClient;
var config = JSON.parse(process.env.APP_CONFIG);
var mongoPassword = '1029384756';

variables.app.use('/client', variables.express.static(__dirname + '/client'));

mongoClient.connect('mongodb://' + config.mongo.user + ":" + mongoPassword + "@" + config.mongo.hostString, function (err, db) {
    if (err) throw err;

    variables.db = db;

    // Routing
    variables.app.get('/', function(request, response) {
        response.sendFile(variables.path.join(__dirname, '/client/index.html'));
    });

    variables.server.listen(process.env.PORT);

    heartbeat.start();

    connection.startListening();
});

我的变量.js:

var http = require('http');
var express = require('express');
var socketIO = require('socket.io');
var path = require('path');
var app = express();
var server = http.Server(app);
var io = socketIO(server);
var db = null;
var onlinePlayers = {};


module.exports = {
    http,
    express,
    socketIO,
    path,
    app,
    server,
    io,
    db,
    onlinePlayers
}

我的connections.js(我的io.on在哪里)

const variables = require('./variables');

module.exports = {
    startListening: function () {
    variables.io.on('connection', function(socket) {
        socket.emit('message', "Testing sending from server.");

        socket.on('message', function(message) {
            console.log(message);
            socket.emit('message', message);
        });

    --Snipped more variables.io.on (ignore {} mistakes, syntax is correct in code)
}

还有我的客户(再次被严厉批评)

var socket = io();
var page = 0;

console.log("Loaded");

window.onload = function() {
    setPage(0);
}

socket.on('message', function(message) {
    console.log(message);
});

将会发生的是:

页面将加载。客户端将打印“已加载”,然后将打印“测试从服务器发送”。 (因为connection.js中连接时的socket.emit)

如果我进入客户端/网页的控制台并输入:

socket.emit('message', "Hello");

我的服务器将打印出“Hello”(正如它应该的那样),但是我的客户端随后不会从服务器获取 socket.emit 来打印“Hello”。

我完全被难住了。有什么帮助吗?

最佳答案

我明白了。在我的代码中的某个时刻(在本例中它位于 setPage(0) 函数内部),具有 socket.ons 的 index.js 文件的标记被删除。这意味着服务器正在发送数据,客户端正在获取数据,但只是没有脚本来告诉它如何处理该数据。

关于javascript - Node.JS 服务器未发送数据(或客户端未接收),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45065297/

相关文章:

javascript - Node JS 异步 I/O 执行

javascript - 传递/路由包含函数原型(prototype)的对象

javascript - 通过 Javascript/jQuery 接收到的字节数和图像的总字节数

javascript - 如何获取像这样的格式(2017 年 3 月 20 日)的当前周日期范围?

javascript - 如何填充元素的方法?

javascript - 如何使用 Breeze.js 设置 DateTimes 的自定义绑定(bind)?

javascript - JS : Text to Image

node.js - 如何在项目之间重用组件

javascript - Connect-busboy : When piping file to write steam, 文件为空或不正确,具体取决于类型

node.js - 在 where 子句中使用 OR 时出错