如何在快速路由中的每个API请求中向特定客户端发出套接字

时间:2019-02-12 23:47:53

标签: javascript node.js socket.io request

我已经请求到API的循环,在此我使用第一个请求中的数据进行其他请求。完成最后一个请求后,我想将数据发送到前端,然后发送给特定用户。我尝试了req.app.io.to(scoketID).emit但它没有用。有没有一种方法可以通过快速路由向前端的特定客户端发送消息?

server.js

var server = https.createServer(httpOptions, app);
var io = require('socket.io')(server);
app.io = io;
  io.once('connection', function(socket){
  console.log("connected")
  socket.on("disconnect",function(){    
    socket.disconnect();
  });
});

results.js

const auth = require("../services/auth");
const rp = require("request-promise")
exports.get = async(req, res, next)=>{
    var i= 0;
    var x = 0;
    const buyerName = []
    const itemID = []
    res.render("sales",{username: data.name})

        rp("URI 1") // VERY FIRST GET AND CALL LOOP
        .then(body => {
            callNext(body)
        })
        .catch(e => {
            console.log(e)
        })


    function callNext(body) {
        let responseJSON = JSON.parse(body);
        if (x>=responseJSON.results.length) { // VERIFY LOOP INDEX TO CALL END FUNCTION
            reqProductsEnd();
        } else {
            rp("URI 2")
            .then(data =>{
                const order = JSON.parse(data)
                buyerName.push(order.buyer.nickname)
                reqProducts(body)
            })
            .catch(e=>{
                console.log(+e)
            })

        }
    }

    function reqProducts(body) {
            rp("URI 3",{
                data: x++
            })
            .then(data =>{
                const item = JSON.parse(data)
                itemID.push(item.thumbnail)
                console.log(i)
                console.log(productName[i])
                i++;
                callNext(body) // CALL LOOP AGAIN
            })
            .catch(e=>{
                console.log(e)
            })       
}
    function reqProductsEnd() {
        console.log(itemID)
        console.log(buyerName)
        req.app.io.to(`${req.app.socket}`).emit('receive item', {buyer: buyerName[i], itemID: itemID[i]}); //this is how i tried, but req.app.socket i've removed app.socket = socket on server's connection. 

    }   
}

view.ejs

$(function () {
var socket = io.connect('https://localhost:3000', { forceNew: true });
socket.on('receive item', function(msg){
    var x = JSON.stringify(msg);
    $("div").append(msg.buyerName);
});
});

0 个答案:

没有答案