简体   繁体   中英

Node.js and socket.io is not allowing to connect and exchange data

I am trying to connect 2 users in 1 room and exchange some data, how can i do that? when i accessing the server getting only : 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);

client:

<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>

Step 1 - run this in server

$ 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

Step 2: make an index.html with following:

<?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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM