Welcome to socket.io. only message
I am making my first app with socket.io and nodejs just as socket.io offical web says, but the only thing I am seeing on the html after running node server.js is "Welcome to socket.io." How can I fix this? Or why is this happening?
The code is as follows:
index.html
<script src="http://my.page/node_modules/socket.io/lib/socket.io.js"></script>
<script>
var socket = 开发者_StackOverflow社区io.connect('http://abogados.pages/');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
server.js
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
I would really appreciate any answer because if not, I can't start with socket.io!
Welcome to socket.io!
1.You should add socket.io js file just like this,
<script src="/socket.io/socket.io.js"></script>
You don't need to address an actual file. socket.io
will take care about this
Hello world would be logged in your browser console, not in your document. Use Firebug or dev tools to check that out.
To do something by your self, emit an event from browser and then use
socket.on('your event', function(){})
and console.log the data you received form client.
I'm new to node and socket.io too! :)
This will work perfectly!!
index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
//socket.emit('my other event', { my: 'data' }); // Line A
});
socket.emit('my other event', { my: 'data' }); //Line B
</script>
server.js
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Perhaps, replacing line B with line A does the trick.Don't know why socket.io didn't check their examples.This is so, because socket.emit() is independent call and wont is somehow not triggered due to the new event of the server.Reason yet unkown, but I was able to get the desired output.
精彩评论