如何从nodejs发送一个variables到所有连接的客户端?

我目前正在为学校开发一个项目,我的想法是创build一个聊天轮盘游戏,所以我正在与nodejs和套接字IO工作我的问题是我如何发送在服务器中生成的随机数的值给我的所有客户,然后执行JavaScript函数来旋转轮盘?

app.js

var express = require('express'); var path = require('path'); var debug = require('debug')('workspace:server'); var http = require('http'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var jquery = require('jquery'); var session = require('express-session')({ secret: "secret", key: 'secret.sid', resave: true, saveUninitialized: true, cookie: { maxAge: 3600000 } }); var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'password', database : 'database' }); connection.connect(); connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution); }); connection.end(); var openid = require('openid'); var app = express(); var port = normalizePort(process.env.PORT || '3000'); app.set('port', port); var server = http.Server(app); var socket = require('socket.io')(server); socket.on('connect', function(){}); socket.on('event', function(data){}); socket.on('disconnect', function(){}); server.listen(port); server.on('error', onError); server.on('listening', onListening); function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } function onError(error) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } } function onListening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; console.log('Listening on ' + bind); } // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(session); function createRelyingParty(req) { var baseUrl = req.protocol + "://" + req.get("host"); return new openid.RelyingParty(baseUrl + "/verify", baseUrl, true, false, []); } // for every request lets make the user session available to the templates app.use(function(req, res, next) { res.locals.user = req.session.user; next(); }); app.get("/", function(req, res) { res.render('index', { title: 'Roulette', session: (typeof req.session.user !== 'undefined') ? req.session.user : '' }); }); socket.on('connection', function(socket){ console.log('a user connected'); socket.on('disconnect', function(){ console.log('user disconnected'); }); }); socket.on('connection', function(socket){ socket.on('chat message', function(msg){ socket.emit('chat message', msg); console.log('message: ' + msg); }); }); var r = require('./SpinGen'); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); 

SpinGen.js(js生成并发送给客户端的号码)

  var express = require('express'); var http = require('http'); var app = express(); var server = http.Server(app); var socket = require('socket.io')(server); setInterval(function() { var rndNum = Math.floor((Math.random() * 34) + 0); var winningNum = rndNum; console.log(winningNum); socket.emit('roulette', winningNum); },10000); 

客户side.js

  var socket = io('http://localhost:3000'); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); socket.on('roulette', function(spin){ spinTo(spin); }); socket.on('error', function(evData){ console.error('Connection Error:',evData); }); 

       

网上收集的解决方案 "如何从nodejs发送一个variables到所有连接的客户端?"

你会发送(发出)随机数到所有连接的客户端 – 它看起来像这样:

 io.emit('random number', randomNumber); 

然后你会在客户端听这样的事件:

 socket.on('random number', function(num){ // num contains the random number // spin the wheel to the random number spinTo(num) }); 

尝试使用io.sockets.emit而不是socket.emit 。 这将发射给所有连接的客户端