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

时间:2015-01-27 06:14:14

标签: jquery node.js socket.io

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

我正在关注本教程:http://socket.io/get-started/chat/

我想知道如何在服务器端设置变量的值,并将该值传递给客户端以在警报中呈现。

我知道这是错的,因为alert(alertMsg);未定义,但这是我的起点:

服务器端:

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>

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

建议?

感谢。

1 个答案:

答案 0 :(得分:1)

客户端必须侦听服务器发送的相同消息名称。现在,您正在使用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);
  });