如何为松弛事件适配器删除.on处理程序

时间:2019-07-02 18:21:11

标签: node.js websocket

我有一个名为slackEvents的事件适配器。每当有人在我的备用应用上发布消息时,它就会触发event。我在websocket函数中具有该功能,因此可以将event从服务器传递到客户端。它工作正常,但是唯一的问题是,如果websocket的初始化次数超过一次,那么event也将触发多次。

我尝试将每件事放入其自己的函数中,但我认为使此事情起作用的唯一方法是:A)能够在ws.send块之外wss.on('connection或B )将slackEvents重置为零.on事件。

const slackEvents = createEventAdapter(process.env.SLACK_SIGNING_SECRET);
const WebSocket = require('ws');
app.use('/slackevents', slackEvents.expressMiddleware());
// received text
wss = new WebSocket.Server({server: server});
// wss.close();

wss.on('connection', function connection(ws) {
    console.log("=================websocket server online=============")
    // receive chat
    slackEvents.on('message', (event) => {
        // console.log(event);
        ws.send(JSON.stringify({text: event.text, userid: event.user, channel: event.channel}));
        console.log(`Received a message event: user ${event.user} in channel ${event.channel} says ${event.text}`);
    });
});

输出将如下所示:

Received a message event: user XXXXXXXX in channel XXXXXXXX says hi again
Received a message event: user XXXXXXXX in channel XXXXXXXX says hi again
Received a message event: user XXXXXXXX in channel XXXXXXXX says hi again
Received a message event: user XXXXXXXX in channel XXXXXXXX says hi again
Received a message event: user XXXXXXXX in channel XXXXXXXX says hi again

0 个答案:

没有答案