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

javascript - Socket.io global sending Function - Node.js - Stack Overflow

programmeradmin0浏览0评论

I build a simple node.js / socket.io app. I need for emitting events a module, that can be accessible through other modules so I can send socket messages when there is for example a new database entry.

Something like this:

function sendWebsocketEvent (whereToSend, EventName, Payload) {
    io.in(whereToSend).emit(EventName, Payload)
  }

I build a simple node.js / socket.io app. I need for emitting events a module, that can be accessible through other modules so I can send socket messages when there is for example a new database entry.

Something like this:

function sendWebsocketEvent (whereToSend, EventName, Payload) {
    io.in(whereToSend).emit(EventName, Payload)
  }

How can I handle that?

I've tried that:

-- app.js --

// Websockets
var http = require('http').createServer(app)
var io = require('socket.io')(http)
http.listen(3000, function () {
  console.log('listening on Port *:3000')
})
require('./WebSockets/socketInit')(io)

-- socketInit.js --

module.exports = (ioInput) => {
  const io = ioInput
  return io
}

-- sendSockets.js --

const io = require('./socketInit')
module.exports = {
  sendWebsocketEvent (whereToSend, EventName, Payload) {
    io.in(whereToSend).emit(EventName, Payload)
  }
}

And I tried to call this function at another module:

const sendSockets = require('../WebSockets/sendSockets')
.
.
.
 sendSockets.sendWebsocketEvent('user', 'databaseUpdate', 'dataToSend')
 .
 .
 .

But this doesn't work.

Is there an other way for getting this done?

  • Chris
Share Improve this question asked Jan 26, 2020 at 18:09 ChrisChris 1473 silver badges11 bronze badges 1
  • Please refer my recently added article on socket.io, this could help you: github./sarveshmahajan89/My-Chat-App – Sarvesh Mahajan Commented Jan 26, 2020 at 18:18
Add a ment  | 

1 Answer 1

Reset to default 6

Inside Server.js

const express = require('express');
const app = express();
const server = require('http').createServer(app)
const io = socket.listen(server);
global.io = io;

const port = process.env.PORT || 5500;
server.listen(port, () => console.log(`%s 
发布评论

评论列表(0)

  1. 暂无评论