调用在回调中定义的函数

时间:2018-10-18 23:22:17

标签: javascript node.js websocket

我很难理解Javascript样式的函数定义。

我有一个Websocket服务器:

var WebSocketServer = require('ws').Server,
wss = new WebSocketServer();

wss.on('connection', function (ws) {
  ws.on('message', function (message) {
    console.log('received: %s from client', message);
  })
  ws.send('hello client');
})

并且我想在调用另一个功能importantEvent()时向连接的客户端发送消息。

function importantEvent(message) {
  //send message to the connected client
  ws.send('hello client');
}

ws.send()内部调用importantEvent()的好方法是什么?

2 个答案:

答案 0 :(得分:2)

我使用EventEmitter做类似的事情来避免强大的模块强度。

// eventManager.js
const EventEmitter = require('events');
class EventManager extends EventEmitter {}
const eventManager = new EventManager();

module.exports = eventManager;

// websocket.js
var eventManager = require('eventManager');
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer();

wss.on('connection', function (ws) {
...
})

function broadcast(data, filter) {
    wss.clients.forEach( ... // depends on library using to web-socket
}

eventManager.on('my-event', function (arg1, arg2) {
    broadcast({arg1, arg2})
});

// in any other files
var eventManager = require('eventManager');

eventManager.emit('my-event', 'hello', 'world');

答案 1 :(得分:1)

这取决于您想吸引哪些客户。在wss.on('connection'...事件中,函数接收到的ws是此事件中连接到服务器的客户端。

要向所有连接的客户端发送消息,您需要使用broadcast method

var WebSocketServer = require('ws').Server,
wss = new WebSocketServer();

function importantEvent(message) {
    // Broadcast to all.
    wss.broadcast = function broadcast(data) {
    wss.clients.forEach(function each(client) {
      if (client.readyState === WebSocket.OPEN) {
        client.send('hello client');
      }
    });
  };
}