【问题标题】:socket io client lost conection when server restarts服务器重新启动时socket io客户端丢失连接
【发布时间】:2020-09-05 19:50:15
【问题描述】:

所以我正在为使用我的服务 (cloudlist.xyz) 的成员创建一个模块。

基本上,我们的服务中有一个投票系统,这个模块使用服务器上的socket io和模块上的socket io客户端建立连接,当有人投票时通知用户

一切正常,但是当我重新启动服务器进行一些维护时,即使服务器再次打开,所有用户都与套接字 io 断开连接

服务器端代码:

     var server = app.listen(process.env.PORT || 3000, () => {
        console.log("Your app is listening on port " + server.address().port)
        }); 

        var io = require('socket.io')(server)
    io.on("connection",function(socket) {
  console.log("Someone Joined to our server api!")
})  

    //that's the part that he emits the event when someone votes

  io.of(`vote/${bot}`).emit("voted", user_votes.val()); 

模块/客户端:

var https = require('https');
const { EventEmitter } = require("events");
var fetch = require('node-fetch')
const io = require("socket.io-client");


module.exports = class Cloud_client extends EventEmitter {
   constructor(id, token) {
      super();

      if (!id) throw new Error("Missing client instance on contructor");
      if (!token) throw new Error("Missing token on constructor");

      this.id = id;
      this.token = token;
      this.socket = io.connect(`https://www.cloudlist.xyz/vote/${id}`, {
         reconnect:true,
         autoConnect:true,
         reconnectionDelay: 1000,
         reconnectionDelayMax : 5000,
         reconnectionAttempts: Infinity      
      });
      this.socket.on("connect", () => this.emit("connected"));
      this.socket.on("disconnect", (...args) => {this.socket.open();

      });
      this.socket.on("voted", (...args) => this.emit("voted", ...args));
  };

这是某人使用该模块的示例:

var cdl = require("cloud-list") 
var cloud_client = new cdl("701456902160121966","5669556617e2a070ada1688") 

cloud_client.on("connected", (data) => { 
console.log(`Connected to the api Server`)
})  

cloud_client.on("voted", (data) => { 
console.log(`Thanks,user ${data.user_name} for voting on us :)`)
})

当我连接到服务器时,它会发送此示例的消息“已连接到 api 服务器”,但是当我重新启动服务器时,我什么也没有收到。已经尝试this.socket.on("disconnect", (...args) => {this.socket.open()});this.socket.on("disconnect", (...args) => {this.socket.connect()}); ,但还是一样,用户无法重新连接。 用户重新连接的唯一方法就是重启他的项目,这很糟糕

【问题讨论】:

    标签: javascript node.js events server socket.io


    【解决方案1】:

    套接字连接需要服务器正在服务。除非您希望它是实时的,否则 Socket.io 似乎不适合投票系统。当服务器重新启动时,客户端会重新启动。

    【讨论】:

      猜你喜欢
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 1970-01-01
      • 2011-04-16
      相关资源
      最近更新 更多