B
B
BonBon Slick2017-10-11 13:28:22
Socket.io
BonBon Slick, 2017-10-11 13:28:22

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>

Processes only the connection event.
I also looked at Google, the example works for others.
https://stackoverflow.com/questions/41752538/sock...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Boris Korobkov, 2017-10-11
@BonBonSlick

var socket = io();

And WHERE should he connect?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question