gpt4 book ai didi

Node.js 和 Socket.io - 无法读取未定义的属性“套接字”

转载 作者:太空宇宙 更新时间:2023-11-03 22:10:30 25 4
gpt4 key购买 nike

我对 Node.js 还很陌生,希望你能帮助我。

我使用 Node (v7.9.0) 以及express (4.15.2) 和 socket.io (1.7.3) 模块来创建一个简单的 Web 服务器并将事件从 Web 服务器发送到连接的客户端。

我正在尝试模块化我的应用程序,并希望在不同的 js 文件上向客户端发出不同的事件。

现在这是我当前的代码:

--- start.js:

// Configure the build-in webserver
var
express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
conf = require('./serverConfig.json');

module.exports = server; // Export to use with uart_functions.js

module.exports.io = io; // Export to use with uart_functions.js

server.listen(conf.port); // Configure the server to port 8080

app.use(express.static(__dirname + '/pages')); // All the website data is in this folder

app.get('/', function(req, res) {
res.sendfile(__dirname + '/pages/index.html'); // Webserver should return the page index.html
});

console.log("Server is opened: http://127.0.0.1:" + conf.port +"/\n");

io.sockets.on('connection', function(socket) {
console.log("Verbunden!!!\n");
io.sockets.emit('chat', {zeit: new Date(), name: "Server", text: "Du bist nun mit dem Server verbunden!"}); // Send Data to Client. This works
});

--- uart_functions.js:

var ioSocket = require('./start.js').io;

function TelegrammID1() {
console.log("RUN ID 1\n");
ioSocket.sockets.emit('chat', {zeit: new Date(), name:'Tester', text: "Das ist ein Test"}); // Send data to client - This doesn't work
}

现在,在 uart_functions.js 文件中,我收到错误:“TypeError:无法读取未定义的属性‘套接字’。”

我明白为什么会发生错误。但我不知道什么以及如何我仍然必须通过 module.export 将文件 start.js 传递到文件 uart_functions.js

关于搜索,我发现了以下内容:Cannot read property 'socket's of undefined when exporting socket.io

不幸的是没有有用的答案。感谢您的帮助

最佳答案

问题是您在函数 TelegrammID1 之外需要 ioSocket,该函数在建立连接时再次导出以运行。在函数 TelegrammId1 中定义变量 ioSocket 并确保导出该函数。

 function TelegrammID1() {
var ioSocket = require('./start.js').io;
console.log("RUN ID 1\n");
ioSocket.sockets.emit('chat', {zeit: new Date(), name:'Tester', text: "Das ist ein Test"}); // Send data to client - This doesn't work
}

关于Node.js 和 Socket.io - 无法读取未定义的属性“套接字”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43604778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com