Problem socket.io NOT working
Details
express [folder]; cd [folder]; npm install;
npm install socket.io
Setup
Client
var socket = io.connect('http://example.com:3000');
socket.on('connect', function() {
console.log('connected');
});
socket.on('message', function(msg){
console.log(msg);
});
socket.on('disconnect', function() {
console.log('disconnected');
});
socket.on('error', function (e) {
console.log('System', e ? e : 'A unknown error occurred');
});
Server
[...]
app.listen(3000);
// socket.io setup
var socket = require('socket.io').listen(app);
// socket.io connection establishment
socket.on('connection', function (client) {
client.send("hello");
console.log("hello", client);
});
Why is connection event never fired?
Took a while to notice... the connection
event is emmited on io.sockets
. In your code this would be
socket.sockets.on('connection', function (client) {
client.send("hello")
console.log("hello", client)
})
You should use io
instead of socket
as the var name to avoid this confusion.
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