简体   繁体   English

Node.js 在多个.js 文件中使用 socket.io

[英]Node.js using socket.io in multiple .js files

I want to be able to write functions in multiple.js files and use the same socket that is create in my main server.js我希望能够在 multiple.js 文件中编写函数并使用在我的主 server.js 中创建的相同套接字

server.js:服务器.js:


var express = require('express')
var app = express()
var http = require('http')
var server = http.createServer(app)
var io = require('socket.io')(server)
var GOR = require('./gor')
var path = require('path');
app.use(express.static(path.join(__dirname, '/public')));

//handles get request and serves index.html
app.get('/', function(req, res) {
    res.sendFile(__dirname + '/public/index.html');
});

//wait for server to start
server.listen(8080,()=>{
  console.log("server started");
  setInterval(emit_data,5000);
  emit_data();
  
  //setInterval(GOR.send_from_another_js,5000);
  //GOR.send_from_another_js(io);
})

function emit_data(){
    io.emit( 'update', "webserver.js");
}

As you can see from the code above, I have a function that emits to socket every 5 seconds and that works fine.正如您从上面的代码中看到的,我有一个 function 每 5 秒发送一次到套接字并且工作正常。 I have confirmed it already.我已经确认过了。

All I want to do now, is to create a seperate.js file and keep all my functions there to make the code look cleaner.我现在想要做的就是创建一个单独的 .js 文件并将我的所有函数都保留在那里以使代码看起来更清晰。 I name another.js file gor.js:我将 another.js 文件命名为 gor.js:

gor.js: gor.js:


//I want to call this function in my webserver.js and transmit this socket
function send_from_another_js(io){
    console.log("function called");
    io.emit( 'update', "another_js");
}

module.exports = {
    send_from_another_js    
}

When I call this function in my server.js, it does not work:当我在我的 server.js 中调用这个 function 时,它不起作用:

server.listen(8080,()=>{
  console.log("server started");
  setInterval(GOR.send_from_another_js,5000);
  GOR.send_from_another_js(io);

})

What is correct way to use the same.io in other.js files?在 other.js 文件中使用 same.io 的正确方法是什么? The above does not work.以上不起作用。

EDIT1编辑1

In my.html, I wait for a message on socket:在 my.html 中,我在套接字上等待一条消息:

window.addEventListener('DOMContentLoaded', () => {
    
    socket.on('update', function(number_to_set) {
    console.log("socket update received");
    document.getElementById('number1').innerHTML = number_to_set;

});
    
    var button = document.getElementById("operation_code_button");
    button.addEventListener("click", function(event){
    var val = document.getElementById("operation_code_input").value;
    console.log("socket clicked, emmiting data");
    socket.emit('button_click',val);
    
});

})

And in my.js file I emit to this socket every 5 seconds:在 my.js 文件中,我每 5 秒向这个套接字发送一次:

server.listen(8080,()=>{
    console.log("server started");
    setInterval(emit_data,5000);
    emit_data();
})

After 5 seconds, I can see that my webpage update data so everything works!!! 5 秒后,我可以看到我的网页更新了数据,一切正常!!!

I want to declare the emit_data function inside another.js file and use it in my main.js file.我想在 another.js 文件中声明 emit_data function 并在我的 main.js 文件中使用它。

The function in my secondary.js file ( gor.js):我的 secondary.js 文件 (gor.js) 中的 function:

function send_from_another_js_1(io){
  io.emit( 'update', data);
}

I want to call it in my main.js the same way I call emit_data我想像调用 emit_data 一样在我的 main.js 中调用它

Edited:(3) Trust it is what you are looking for...编辑:(3)相信这是你正在寻找的......

"server.js" “服务器.js”

const content = require('fs').readFileSync(__dirname + '/index.html', 'utf8');
const httpServer = require('http').createServer((req, res) => {
// serve the index.html file
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Length', Buffer.byteLength(content));
res.end(content);
});

const io = require('socket.io')(httpServer);

const apple = require("./File2.js")
apple.send_from_another_js_1(io);
apple.send_from_another_js_2(io);

var port = 3000; //wamp server
var prompt = 'Open browser at http://localhost:'
httpServer.listen(port, () => {
console.log(prompt, port);
});

"File2.js" “文件2.js”

function send_from_another_js_1(io){
  io.on('connection', function (socket) {
  socket.on('file2_1_EventTrigged', function (data) {
  socket.emit('update1', "send_from_another_js_1(io) : "+ data);
  console.log("+++ function send_from_another_js_1(io) called");
  });
 });
}

function send_from_another_js_2(io){
  io.on('connection', function (socket) {
  socket.on('file2_2_EventTrigged', function (data) {
  socket.emit('update2', "send_from_another_js_2(io) : "+ data);
  console.log("... function send_from_another_js_2(io) called");
  });
 });
}

module.exports = {
 send_from_another_js_1,
 send_from_another_js_2
}

"index.html" “索引.html”

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="Content-Type" content="text/html">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <meta name="keywords" content="HTML, CSS, JavaScript">
 <meta name="author" content="Dr.Chaiya Tantisukarom">
 <meta http-equiv="Cache-Control" content="public, max-age=31536000">
 <title>NodeJS socket.io</title>
</head>
<body>
 <h1 style="text-align: center;">Hello another world</h1>
 <div style="text-align: center;">
  <span>
   <button onclick="file2_1()">file2_1</button>
  </span>
  <span>
   <button onclick="file2_2()">file2_2</button>
  </span>
 </div>

<script src="/socket.io/socket.io.js"></script>
<script>
 var socket = io();
 socket.on('connect',()=>{
  //alert('Connected');
 })

function file2_1(){
 socket.emit('file2_1_EventTrigged', "Hello file2_1, how are you today?");
}
socket.on('update1', (data)=>{
 alert(data);
})

function file2_2(){
 socket.emit('file2_2_EventTrigged', "Hi file2_2, trust you are ok.");
}
socket.on('update2', (data)=>{
 alert(data);
})

</script>
</body>
</html>

Cheers !!!干杯!!!

You need to wait for your server to get initialized.您需要等待服务器初始化。 You are calling your function before socket.io is ready.在 socket.io 准备好之前,您正在调用您的 function。 That's why io.emit function is 'undefined'.这就是为什么 io.emit function 是“未定义”的原因。

server.listen(8080,()=>{
  GOR.send_from_another_js(io);
})

When you call this:当你这样称呼时:

server.listen(8080,()=>{
    console.log("server started");
    setInterval(GOR.send_from_another_js,5000);
    GOR.send_from_another_js(io);
})

setInterval() isn't providing a parameter for GOR.send_from_another_js() , so io becomes undefined. setInterval()没有为GOR.send_from_another_js()提供参数,因此 io 变为未定义。

To fix this, I would use a second lambda expression inside of your setInterval() call.要解决此问题,我会在您的setInterval()调用中使用第二个 lambda 表达式。

server.listen(8080, () => {
    console.log("server started");
    setInterval(() => {
        GOR.send_from_another_js(io);
    }, 5000);
    GOR.send_from_another_js(io);
});

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

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