Node.js和socket.io不允许连接和交换数据



我正在尝试连接一个房间中的两个用户并交换一些数据,我该怎么做?当我访问服务器时只得到:abba

server.js:

var http = require('http');
var app = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('abba');
});
var io = require('socket.io').listen(app);
var messageExchange = io
    .of('/play')
    .on('connection', function (socket) {
        socket.channel = "";
        socket.on("joinChannel", function (data) {
            socket.channel = data.channel;
        });
        socket.on("message", function (data) {
            socket.broadcast.emit("message", {
                channel: socket.channel,
                message: data.message
            });
        });
     });

app.listen(3000);

客户端:

<script>
var chat = io.connect('//talk.test.com:3000/play');
var channel = "ciao";
chat.on("connect", function () {
    chat.emit("joinChannel", {
        channel: channel
    });
});
chat.on("message", function (data) {
    if (data.channel == channel) {
        alert(data.message);
    }
});
// Send a message!
chat.emit("message", { message: "hola" });
</script>

步骤1-在服务器中运行

$ cat server.js
var io = require('socket.io').listen(3000);
io.sockets.on('connection', function (socket) {
  io.sockets.emit('this', { will: 'be received by everyone'});
  socket.on('joinChannel', function (from, msg) {
    console.log('I received a private message by ', from, ' saying ', msg);
    io.sockets.emit('message', {channel: from.channel, message: 'Got it?' } );
  });
  socket.on('disconnect', function () {
    io.sockets.emit('disconnected');
  });
});
$ node server.js

第2步:制作一个包含以下内容的index.html:

<?php
$room = $_GET['r'];
?>
<!doctype html>
<html>
<head>
<script src='//code.jquery.com/jquery-1.7.2.min.js'></script>
<script src='//talk.domain.com:3000/socket.io/socket.io.js'></script>
<script>
var chat = io.connect('//talk.domain.com:3000');
var channel = '<?php echo $room;?>';
chat.on("connect", function () {
    chat.emit("joinChannel", {
        channel: channel,
        message: 'OKOKOKOKOKOK'
    });
});
chat.on("message", function (data) {
    if (data.channel == channel) {
        alert(data.message);
    }
});
</script>
</head>
<body>
</body>
</html>

相关内容

  • 没有找到相关文章

最新更新