A
A
Andrew2019-10-15 21:54:40
Node.js
Andrew, 2019-10-15 21:54:40

How to use WebSocket in node.js modules?

WebSocket is initialized in the main file, this is all clear and obvious. Separately, in the main file there is a clients object, with information about connected clients. It's also simple so far.
But what to do when I want to trigger an event for a specific user inside any other module, for example, from a controller?
index.js

// Тут стандартные импорты
const WebSocket = require('ws')
const http = require('http')
const express = require('express')
const app = express()
const server = http.createServer(app)
const wss = new WebSocket.Server({ server })

const clients = {}
wss.on('connection', (ws, req) => {
  // тут происходит всякое с сокетами
})

server.listen(8081, () => {
  console.log('Сервачок запущен')
})

/controllers/UserController.js
router.post('/sendMessage', (req, res) => {
  // Хочу отправить сообщение через вебсокет вот тута 
})

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question