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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With