我已经制作了使用Socket的电子应用程序。IO在后端(NodeJS)和前端(Jquery)之间进行通信。
我已经发送数据io.on('connection', (socket) => { socket.emit (.....) })
我的问题是我不能从API调用发送数据。
让我告诉你这个例子。
const express = require('express')
const app = express()
const http = require('http')
const server = http.createServer(app)
const { Server } = require("socket.io");
const io = new Server(server);
app.set('socketIo', io);
app.get('/api/run', (req, res) => {
const ioEmitter = req.app.get("socketIo");
ioEmitter.emit('data', 'some data'); // not working
// ioEmitter.to(~some socket id~).emit('data', 'some-data')
// not working either. I can't get anything to client side
})
客户端代码
socket.on('data', (msg) => {
console.log(msg)
})
从API调用中获取数据对我(项目)来说是强制性的。
可以直接使用io。发射而不是ioEmitter。