简体   繁体   中英

How to send websocket message to client from the serverside

Hello I have two backends laravel and Nodejs and There will be one frontend.

So if the front end requests something on laravel and laravel requests to node and Node has to send a message to the client through WebSocket. How to do It?

Index.js

const app = require('express')();
const http = require('http');
const WebSocket = require('ws')

//initialize a simple http server
const server = http.createServer(app);
app.get('/', function(req, res) {
  res.sendFile(__dirname + '/index.html');
});
let sendNotification;
//initialize the WebSocket server instance
const wss = new WebSocket.Server({ server });
let socketapi = require('./socketapi')
socketapi.start(wss)
//start our server
server.listen(process.env.PORT || 5555, () => {
    console.log(`Server started on port ${server.address().port} :)`);
});

socketapi.js

module.exports ={
    start: (wss) => {
        wss.on('connection', (ws) => {
            console.log('connected!!!');
            console.log(socketIds)
            //connection is up, let's add a simple simple event
            // triggerMessage('data');
            ws.id=uuidv4()
            ws.on('message', (message) => {
                console.log('received: %s', message);
                // ws.send(`Hello, you sent -> ${message}`);
            });
        }
    }
 }

Now I want to use this socket in the controller file and send it as I get a request.

When I export and import socket it logs as undefined.

我已将 ws 存储在具有特定 ID 的数组中,并且该 ID 与 DB 中的数据相关联,因此我可以使用该 ID 获取 ws 并在函数调用时通过该 ws 发送

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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