socket.io cause php redis read error on connection?

Viewed 212

I use php(laravel 5.8) to broadcast, and I use laravel-echo-server, it's work. But!!! recent I need to something by my self. And I write a socket service by ndoejs. This is my code

const jwt = require('jsonwebtoken');
const server = require('http').Server();
const io = require('socket.io')(server);

... 

// ==== The question is here =====================
const Redis = require('ioredis');
const redis = new Redis({
  port: REDIS_PORT,
  host: REDIS_HOST,
  password: REDIS_PASSWORD
});

redis.psubscribe('myTestChannel.*');

redis.on('pmessage', function(pattern, channel, message) {
  console.log(channel, message);
  const object_message = JSON.parse(message);
  io.sockets.emit(channel, object_message.data);
});
// ==== The question is here =====================

io.sockets.use(function (socket, next) {
  if (socket.handshake.query && socket.handshake.query.token){
    // auth
  } else {
    next(new Error('Authentication error'));
  }
}).on('connection', function(socket) {
  console.log('==========connection============');
  console.log('Socket Connect with ID: ' + socket.id);

  socket.on('join', (data) => {
    ... do something
  });

  socket.on('disconnect', () => {
    ... do something

  })
});

server.listen(LISTEN_PORT, function () {
  console.log(`Start listen ${LISTEN_PORT} port`);
});

It's work, but running a long time, my php get a error message, phpredis read error on connection. I'm not sure the real reason. But I guess is about my socket, because I use laravel-echo-server is great.

I'm not sure my redis.psubscribe's position is right? Maybe this cause a long time connection and cause php read error on connection?

I should move the redis.psubscribe into on('connection') and unsubscribe when disconnection?

I want to know the redis.psubscribe is the main cause the problem? Thanks your help.

0 Answers
Related