Answer the question
In order to leave comments, you need to log in
Why doesn't socket.on('disconnect') work?
Everything works up to this point, there are no errors in the console.
//server
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){
console.log('a user connected')
//emit message to all front-end clients
io.emit('chat message', 'some message sent to all users');
//handling disconnects
socket.on('disconnect', function() {
alert(123); // сюда не заходит
io.emit('chat message', 'some user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
//client side
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
//on io.emit from backend (notice 'chat message' event has same name as server side)
// и так же не работает так как выше io.emit() не отработал :(
socket.on('chat message', function(msg){
console.log('Yay, I got a message back from the server: ', msg)
//handle the message however you would like
$('#messages').append($('<li>').text(msg));
});
</script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question