Razvan Alex Razvan Alex - 2 months ago 4
HTML Question

Socket.io simple node app is not working

I have this little socket room app, but for a reason is not working. I'm trying to make the user join the room on click and display an alert, can't figure out the issue, I'm kinda new to sockets and can't even get this simple app working.. This is my code

////app.js

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

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

io.on('connection', function(socket) {
socket.on('room', function(room) {
socket.join(room);
});
});

room = "abc123";
io.sockets.in(room).emit('message', 'what is going on, party people?');

http.listen(3000, function(){
console.log('listening on localhost:3000');
});


////index.html

<!DOCTYPE html>
<html>

<head>
<title>flip</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

</head>

<body>
<button>Join the room!</button>
</body>
<script>
var socket = io.connect();

// let's assume that the client page, once rendered, knows what room it wants to join
var room = "abc123";

socket.on('connect', function() {
$('button').click(function() {
socket.emit('room', room);
})

});

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

</script>

</html>

Answer

On the client side you have to:

 var socket = io.connect('http://localhost:3000');

On the server side:

io.on('connection', function(socket) {
    socket.on('room', function(room) {
        socket.join(room);
        room = "abc123";
        io.to(room).emit('message', 'what is going on, party people?');
    });
});

You can not emit until you receive the connection.

Comments