如何从nodejs向所有连接的客户端发送变量?

时间:2015-12-21 22:33:02

标签: javascript node.js express socket.io

我目前正在为学校做一个项目,我的想法是创建一个带聊天的轮盘游戏,所以我正在使用nodejs和socket 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);
  });

2 个答案:

答案 0 :(得分:1)

尝试使用io.sockets.emit代替socket.emit。这将发送给所有连接的客户端

答案 1 :(得分:1)

您可以将随机数发送(发送)到所有连接的客户端 - 它看起来像这样:

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)
  });