Socket.io(1.x).to(房间)没有工作,但没有工作

时间:2014-08-01 13:56:46

标签: javascript ios node.js sockets socket.io

我正在构建一个简单的消息服务器,并且使用socket.broadcast.emit()可以很好地工作,但是如果您使用socket.broadcast.in(room).emit()它不能连接。我在下面提供了服务器代码和客户端代码。

服务器

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Parse = require('parse').Parse;

var room;

app.get('/', function(req, res){
  res.sendfile('index.html');
});

// When a new connection is launched
io.on('connection', function(socket){

  console.log('user connected: '+socket.id);

  //========== INIT connection =========
  // once a client has connected, we expect to get a ping from them saying what room
  // they want to join
  socket.on('room', function(data) {
    room = data;

    socket.join(room);

    console.log('  + User: '+socket.id+' - joined Room: ['+room+']');
    console.log('  + User: '+socket.id+' - has Rooms: ['+socket.rooms+']');

    // Display all sockets connected to room
    inRoom(room);
  });

 //======== Delegates messages ========
 socket.on('message_send', function(data){

    var JSONdata  = JSON.parse(data);
    var room_l    = JSONdata.chat_id;
    var msg       = JSONdata.message;

    console.log('Room: ' + room_l + ' - Message: ' + msg);

    // Send message
    //io.emit('message_received', msg);
    //socket.broadcast.emit('message_received', msg);
    io.in('TZRfM7V5HH').emit('message_recieved', msg);
    //io.to(room_l).emit('message_received', msg);

    // Save message to parse
    parseSAVE(data);
  });
});

客户端

<script>
  var socket = io();
  var msg = $('#m').val();

  var room = 'TZRfM7V5HH';

  $( document ).ready(function() {
    socket.emit('room',room);
    socket.emit('message_send', '{"chat_id":"'+room+'","message":"yoyoyo shits to hype"}');
  });

  $('form').submit(function(){
    $msg = $('#m').val();
    socket.emit('message_send', '{"chat_id":"'+room+'","message":"'+$msg+'"}');
    $('#messages').append($('<li>').text($msg));
    $('#m').val('');
    return false;
  });
  socket.on('message_received', function(msg){
    $('#messages').append($('<li>').text(msg));
  });
</script>

我整个星期一直在玩这个,我似乎无法弄清楚我的实施有什么不对,任何帮助或指示都会非常感激!

0 个答案:

没有答案