将服务器端variables发送到客户端node.js和socket.io

我要问一个真正的问题。 因为我一直在阅读文档,并在这里挖掘,而它只是没有进入我的大脑。

我正在学习这个教程: http : //socket.io/get-started/chat/

我想知道如何在服务器端设置variables的值,并将该值传递给客户端,以提醒。

我知道这是错误的,因为alert(alertMsg); 回来undefined,但这是我的出发点:

服务器端:

 var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var fs = require('fs'); var port = process.env.PORT || 3000; var alertMsg = 'alert message goes here'; app.get('/', function(req,res){ res.sendFile(__dirname + '/index.html'); }); io.on('connection', function(socket){ console.log('a user connected'); socket.on('connect', function(alertMsg){ io.emit('alert: ' + alertMsg); }); socket.on('chat message', function(msg){ console.log('message: ' + msg); io.emit('chat message', msg); // send the message to everyone }); socket.on('disconnect', function(){ console.log('user disconnected'); }); }); http.listen(3000, function(){ console.log('listening on %d', port); }); 

客户端:

 <!doctype html> <html> <head> <title>Socket.IO chat</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> </head> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.js"></script> <script> var socket = io(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); // I know this isn't right ATM... socket.on('connect', function(alertMsg){ alert(alertMsg); }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); </script> </body> </html> 

我肯定错过了一些非常明显的东西。 我只是看不到它。

build议?

谢谢。

客户端必须侦听服务器发送的相同消息名称。 现在,通过使用io.emit('alert: ' + alertMsg);从服务器发送可变消息名称io.emit('alert: ' + alertMsg); ,所以没有办法在客户端收听特定的消息。

将服务器更改为:

 io.emit('alert', alertMsg); 

添加到客户端:

 socket.on('alert', function(msg) { alert(msg); }); 

看看这是如何发送和收听相同的消息名称?


然后,也删除这个代码,因为在连接时没有alertMsg被发送(稍后会有):

  // I know this isn't right ATM... socket.on('connect', function(alertMsg){ alert(alertMsg); });