简体   繁体   中英

notification system with php and socket.io

Im trying to build an notification system with php and socket.io. The idea is, the clients connect to socket.io and are waiting for notification. A PHP script connects to socket.io via curl on another port and posts the update even, which gets passed to the connected clients. The clients are identified via an id they send in a message after the connection event. I Store the socket variable associated to the user_id. Everything works fine, but after some time the script stops working. It seems that after some time the socket variable which is stored in an array. However my server-code is posted below

var notification_port = 8001;
var oak_port          = 8002;

var io = require('socket.io').listen(notification_port);
var clients = new Array();

io.sockets.on("connection", function(socket){
   socket.on("__identification", function(message){
      if (message.id){
         console.log("user with session id " + message.id + " connected!");
         var sockets = clients[message.id];
         if (!sockets){
            sockets = new Array();
         }
         sockets.push(socket);
         clients[message.id] = sockets;
      }
   });
});

var url  = require('url');
var oakListener = require('http').createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});

  var url_parts = url.parse(req.url, true);
  var query = url_parts.query;

  var sockets = clients[query.id];
  if (sockets){
     for (var i = 0; i < sockets.length; i++){
        sockets[i].emit("notification", query);
      }
      res.end('ok');
  } else {
     res.end('failed');
  }
}).listen(oak_port);

you have to add a handler for disconnect like explained below:

socket.on('disconnect', function () {
    //delete socket from sockets;
});

The problem was, that the connection gets lost about every minute. You have to gargabe collect in the "disconnect" function and re initializing the connection in the "connection" function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM