Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.emit and socket.on do not work in node.js

I tried to connect my chrome browser to NodeJs Server. All the code works great on other machine. but when i run it on my machine neither it gives an error nor it gives a success. here is the code

Server Code:

var server =  http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

var io = require('socket.io').listen(server);
io.sockets.on('message', function (socket) {
    socket.emit('news', { hello: 'world' });

});

and Here is the Client Code.

<script>
        var socket = io.connect('http://localhost:3000/');
       //console.log(socket);
        socket.on("message",function(data){
            console.log(data);
        })
    </script>

Kindly correct me where I am doing it wrong. console.log() in client doesnot work. I tried to check it in chrome debugger using breakpoints but it never goes to that point.

like image 415
Hsm Sharique Hasan Avatar asked Dec 11 '22 13:12

Hsm Sharique Hasan


1 Answers

You are missing some code:

io.sockets.on('connection', function (socket) {
  socket.on('message', function (data) {
    socket.emit('news', { hello: 'world' });
  });

  socket.on('another-message', function (data) {
    socket.emit('not-news', { hello: 'world' });
  });
});

Taken from socket IO website. For this to work you need to start by sending a 'message' from the client, something in the lines of:

<script>
  var socket = io.connect('http://localhost:3000/');
  socket.on('connect',function(){
    socket.emit('message', 'Hello server');
  });

  socket.on('news', function(msg) {
    alert('News from server: ' + msg.hello);
  });
</script>
like image 153
leko Avatar answered Jan 02 '23 10:01

leko