Socket.io Emit等待回调

时间:2019-04-14 13:18:07

标签: javascript html node.js socket.io

我创建了一个在本地主机上运行Wheel的nodeJS应用程序:3000。 现在,我创建了一个套接字,向其发送广播,并调用一个使车轮旋转的按钮单击事件。

问题在于,当我旋转车轮时,无法让该方法等到获得输出结果。

App.js

const express = require("express");
const sleep = require("sleep");
const app = express();
var _http = require('http');
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.use(express.static('public'));

var _result = 'No result';

http.listen(3000, function () {
console.log('Check the Wheek on http://localhost:3000');
});

io.on('connection', function (socket) {
socket.on('spin', function (msg) {
_result = msg;
console.log(_result);
});
});

app.get('/spin', (req, res) => {
io.emit('spin', '');
res.status(200).send({ message: 'Wheel Spinned' });
});

app.get('/wheelResults', (req, res) => {

var options = {
    host: 'localhost',
    port: 3000,
    path: '/spin',
    method: 'GET'
};
_http.request(options, function (_res) {
    _res.on('data', function (chunk) {
        res.status(200).send({ message: _result });
    })
}).end();
});

////////////////// INDEX.html代码/////////////

<script> const spinButton = document.querySelector('.SpinButton'); $(function () { var socket = io(); socket.on('spin', function(msg){ spinButton.click(); }); $('.WheelResult').bind("DOMSubtreeModified",function(){ socket.emit('spin', $('.WheelResult').val()); }); }); </script>

0 个答案:

没有答案