首页 > 解决方案 > socket.io 在连接时导致 php redis 读取错误?

问题描述

我使用 php(laravel 5.8) 进行广播,我使用laravel-echo-server,它的工作。但!!!最近我需要自己做点什么。我socket service用 ndoejs 写了一个。这是我的代码

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`);
});

它可以工作,但是运行了很长时间,我的 php 收到一条错误消息,phpredis read error on connection。我不确定真正的原因。但我猜是关于我的套接字,因为我使用 laravel-echo-server 很棒。

我不确定我redis.psubscribe的位置是否正确?也许这会导致长时间连接并导致连接时出现php读取错误?

断开连接时我应该移入redis.psubscribe并取消订阅吗?on('connection')

我想知道redis.psubscribe问题的主要原因是什么?谢谢你的帮助。

标签: phpnode.jsredissocket.io

解决方案


推荐阅读