【问题标题】:Using Socket.io emit in a different module (Node.js)在不同的模块(Node.js)中使用 Socket.io 发射
【发布时间】:2020-07-11 06:03:41
【问题描述】:

我一直在努力让这个工作一天,我希望有人可以为我提供一些基础,因为我试图阅读这个但收效甚微。

应用目的:我的应用从用户那里获取用户名和密码,启动一个运行 puppeteer 的模块以自动执行任务,同时为用户提供 puppeteer 进度的实时更新。

同时连接的 2 个用户可以输入不同的凭据,并且 puppeteer 应该同时运行,向其工作的特定用户输出进度。

我正在使用用 express 生成器创建的 node.js + express + ejs + socket.io。

文件结构如下:

bin/
--www.js
app.js
scraper.js
views/
--index.js
routes/
--index.ejs
public/
  ...

我有 socket.io 在配置服务器的www.js 模块中工作,我设置的是用户单击前端的提交按钮,socket.io 发出接收到的唯一消息(在 www.js 中)并在 scraper.js 中调用函数 launchScraper

我希望 launchScraper 然后向该个人用户发送实时更新。即成功登录,完成工作等。

问题:我似乎无法让 scraper.js 向该唯一用户发送消息(使用他们的 socket.id),我想我错过了一些理论。这是我的代码:

www.js

const scraper = require('../scraper');
const socketio = require('socket.io');
...
const server = http.createServer(app);
const io = socketio(server);
...
io.on('connection', (socket) => {
console.log('New connection: '+ socket.id);
...
  socket.on('launchScraper', (socket) =>{
  console.log('received client launchScraper');
  scraper.launchScraper(io,userCredentials);
  })

scraper.js

 const puppeteer = require('puppeteer'); 

//This emits the message to all users, but I've tried variations sending `socket.id` in etc and I cannot seem to get it to work.
function emitMessage(io,msg){
io.emit('message',msg);
console.log(msg);
}

async function launchScraper(io,userData) {

emitMessage(io, 'Launching Scraper...'); //Sending io in
const browser = await puppeteer.launch({..});
const page = await browser.newPage();
...

谁能帮助或建议更好的方法来做到这一点? 我只是不想要很多代码是 www.js,因为我不相信代码应该在那里..

我是 Node 的新手,我很难理解实例、构造函数等。

【问题讨论】:

    标签: javascript node.js express socket.io emit


    【解决方案1】:

    原来我需要用我的请求发送“socket”而不是“io”实例。

    这样做似乎可以解决问题。

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多