【问题标题】:How to send data to socket.io from react?如何从反应向socket.io发送数据?
【发布时间】:2020-06-24 18:15:19
【问题描述】:

我以前从未使用过 Socket.IO,所以这对我来说很新。

我在 react 中有一个出租车应用程序,它将通过 Socket.IO 将新订单作为事件发送,但我没有看到任何错误或响应。

服务器端是这样的:

client.on('newOrder', function(data){
    socketController.newOrder(data, io, client);
});

newOrder: function(data, io, client) {
    order.create(data, io, client, function(response){});       
}

Order.prototype.create = function (data, io, client, callback) {

    console.log("ORDER DATA = " + JSON.stringify(data));

    let luggage = 0;
    if (typeof data.luggage !== 'undefined')
        luggage = data.luggage;

    let insertData = {
        client_id: data.id_client,
        start_address: data.origin.name,
        start_lat: data.origin.latitude,
        start_lng: data.origin.longitude,
        end_address: data.destination.name,
        end_lat: data.destination.latitude,
        end_lng: data.destination.longitude,
        options: JSON.stringify(data.options),
        car_options: JSON.stringify(data.car_options),
        car_type: data.car_type,
        passengers: data.passengers,
        luggage: luggage,
        payment_method: data.payment_method,
        profile_id: data.profile,
        profile_type: data.profile_type
    };

    if (data.schedule_time != null && data.schedule_time.length > 0) {
        insertData.schedule_time = data.schedule_time
    }

    db.query("INSERT INTO orders SET ?", insertData,
        function (err, results, fields) {
            if (err) {
                console.log("Order.create [ERROR: " + err + "]");
                return callback({ error: true, message: err });
            }

            data.id_order = results.insertId;

            const timeInsert = {
                order_id: data.id_order,
                new: new Date().toISOString().slice(0, 19).replace('T', ' ')
            };

            db.query("INSERT INTO orders_timestamps SET ?", timeInsert, function (err, results, fields) { });

            client.emit("orderSaved", { "id_order": data.id_order });
            getOrder(data.id_order, function (order) {

                sendOrdersToDriver(data, order, io, function (data) {
                    console.log("Order.create [SUCCESS]");
                    return callback(data);
                });
            });


        }
    );

};

客户端是这样的

const data = {
    id_client: user.id,
    car_type: "executive",
    car_options: [],
    passengers: 1,
    luggage: 2,
    payment_method: "cash",
    options: [],
    origin: { name: pickUp, latitude: pickUpCoordinates.lat, longitude: pickUpCoordinates.lng },
    destination: { name: dropOff, latitude: dropOffCoordinates.lat, longitude: dropOffCoordinates.lng },
    schedule_time: new Date(),
    profile: "",
    profile_type: "owner"
}
socket.emit("newOrder", data, function (response) {
    console.log('emit response', response);
});

【问题讨论】:

    标签: node.js reactjs socket.io


    【解决方案1】:

    编辑 1: 让我试着解释一下这个回调是如何工作的,

    // here we are at the client-side
    // so here from client side i'm sending a data and a callback
    // socket.emit('event-name', data, callback); signature
    socket.emit('some-event', { a: true }, function(dataFromServer) {
        console.log(dataFromServer);
    });
    
    // here we are at server-side
    socket.on('some-event', function(data, callback) {
        // we are getting the data first argument and callback second
        // let's say we are testing if data has a === true;
        if(data.a) { // same as data.a === true
           // here we are gonna send 'hi' to callback
           return callback('hi the data was valid for me');
        }
        // otherwise we are assuming that data wasn't valid
        return callback('your data is not okey mate!');
    });
    

    因此,如果您从客户端发送包含 { a: true } 作为道具的数据,您应该会看到回调安慰 'hi the data was valid for me' this。

    否则,如果它不包含aa: false,那么您应该会从客户的回调中看到'your data is not okey mate!'

    考虑到这个情景;去找你的代码并检查 =)

    首先请检查您是否在您的前端socket.connected === true

    第二次在这里你通过你的emit发送datacallback

    socket.emit("newOrder", data, /*this is your callback*/function (response) {
        console.log('emit response', response);
    });
    

    在您的服务器上,您只从客户端获取数据。

    // needs to be like this
    client.on('newOrder', function(data, callback) {
        socketController.newOrder(data, callback, io, client);
    });
    // same with 
    newOrder: function(data, callback, io, client) {
         // you probably dont need to send this empty callback cause actualy callback 
         // coming after `data`, `callback`
        order.create(data, callback, io, client); //function(response){});       
    }
    
    // same with 
    Order.prototype.create = function (data callback, io, client) {
    ...
    
      sendOrdersToDriver(data, order, io, function (data) {
        console.log("Order.create [SUCCESS]");
        // here you are calling it so it needs to work if
        // your `sendOrdersToDriver` function actually calls it's 
        // own callback?
        return callback(data);
      });
    }
    

    【讨论】:

    • 我查过socket.connectedtrue。现在从你的第二点开始,我不应该通过emit发送日期?
    • date 是什么意思?
    • github.com/halilcakar/socketio-emit-callback-example克隆这个例子,看看我为你做了一个小例子的代码
    • data not date 抱歉打错了
    • 是的,如果你需要从客户端向服务器发送一些东西,你可以,上面还发送一个data
    猜你喜欢
    • 2014-07-28
    • 1970-01-01
    • 2013-01-03
    • 2014-09-30
    • 2018-01-29
    • 1970-01-01
    • 2020-09-12
    • 2018-05-27
    • 2016-01-08
    相关资源
    最近更新 更多