2

I am using nodejs v0.11.0-pre and socket.io version 0.9.11 and I want to detect socket disconnection on client side. I am using this code to do alert on disconnect this but it seems that I am doing some thing wrong any one can help, thanks

Client:

<script src="http://127.0.0.1:4000/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script language="javascript" type="text/javascript">
  var socket = io.connect('127.0.0.1',{port:4000});
  console.log("connected");  
  socket.on('disconnect', function () {
        alert('disconnected');
    });
</script>

Server:

var http = require('http');
var app = http.createServer().listen(4000)
,io = require('socket.io').listen(app);
io.sockets.on('connection', function (socket) {
    console.log("client has established :" + socket.id);
socket.on('disconnect', function () {
    console.log("client has disconnected :" + socket.id);
});       
});

Every thing works fine on the server, but there is no alert on disconnect on client.

Misha Zaslavsky
  • 8,414
  • 11
  • 70
  • 116
mohamed.alsum
  • 53
  • 1
  • 7

2 Answers2

4

Do as follows:

<script src="/socket.io/socket.io.js"></script>

<script language="javascript" type="text/javascript">
    var socket = io.connect('127.0.0.1:8080');

    socket.on('connect', function() { console.log("connected"); });
    socket.on('disconnect', function () { console.log("disconnected"); });
</script>

and your listener port must be same as the connect uses that.

Reza Ebrahimi
  • 3,623
  • 2
  • 27
  • 41
1

There is no such thing as connection on server side and/or browser side. There is only one connection. If one of the sides closes it, then it is closed (and you cannot push data to a connection that is closed obviously). Source: https://stackoverflow.com/a/18147207/973155

You can however close the connection yourself from the client side:

socket.disconnect();
Community
  • 1
  • 1
Farhan Ahmad
  • 5,148
  • 6
  • 40
  • 69