【问题标题】:why socket.disconnect() on client side doesn't fire disconnect event on the server?为什么客户端的 socket.disconnect() 不会在服务器上触发断开事件?
【发布时间】:2018-10-03 15:23:21
【问题描述】:
I SOLVED MY PROBLEM WİTH THİS CODE BLOCK


var io = require('socket.io')(server, {
  pingInterval: 10000,
  pingTimeout: 5000,
}).listen(server)

我正在使用 socket.io 制作聊天应用程序。但是如果我没有在 15 或 20 秒内发生事件,我的应用程序将断开与 socket.io 的连接。我想在应用关闭时断开连接

服务器端代码;

var server = http.createServer(app);
var io = require('socket.io').listen(server);

io.on('connection', function(socket){
let chatroom;
console.log("User Connected");
io.sockets.emit('connected', "12345");
socket.on('chatRoom', function(room) {
socket.join(room);
chatroom = room;
});

socket.on('messageData', function(msg){
  io.sockets.in(chatroom).emit('messageData', msg);
});
 socket.on('disconnect', function(msg){
  console.log("User DisConnected"); 
});

});

客户端套接字类

import React, { Component } from 'react';
import io from "socket.io-client";

class socketio extends Component{


    static socketConnect = () =>{
       this.socket=io("http://xxx.xxx.xxx.xxx:3000",{jsonp:false});
    }

    static getSocket = () =>{
        return this.socket;
    }
}

export default socketio;

客户端聊天屏幕代码;

import socketio from '../Classes/socketio';
this.socket = socketio.getSocket();

      this.socket.emit('chatRoom', this.state.chatID);

            this.socket.on("messageData",(data) =>{               

            });

【问题讨论】:

  • 请向我们展示客户端和服务器上的相关实际代码。您的问题本身听起来不像是一个问题,所以我们需要看看您在实际代码中做了什么。如果您向我们展示相关代码,这里关于代码的问题几乎总能得到更快、更准确的答案。
  • 感谢@jfriend00 的评论,我添加了代码块
  • 调用socket.disconnect()的代码在哪里?
  • 此外,您似乎在 socketio 类中滥用了 this、静态方法和粗箭头函数。我不知道这是否会导致您的特定问题,但它确实是很糟糕的代码,很容易导致问题,并且肯定会导致对套接字实际存储位置的混淆。
  • 我的问题是,如果我不发送消息并且第二个用户在 15 或 20 秒内不发送消息。服务器自动断开我的连接。

标签: node.js react-native socket.io


【解决方案1】:

您在静态方法中的远箭头函数中使用this 真的非常令人困惑。 this 值可能是您模块中的 this 值,这可能是 module 本身。在任何情况下,这都不是存放套接字的好地方,而且非常非常混乱。


我不知道这是否能解决您的主要问题,但您可以通过更改为来解决您对this、静态方法和粗箭头函数的使用:

import React, { Component } from 'react';
import io from "socket.io-client";

// module level variable, can only be one connected socket with this design
let socket;

class socketio extends Component{
    static function socketConnect() {
       socket = io("http://xxx.xxx.xxx.xxx:3000",{jsonp:false});
    }

    static function getSocket() {
        if (!socket) {
            throw new Error("Must call socketConnect() before getSocket()");
        }
        return socket;
    }
}

export default socketio;

就个人而言,我不知道您为什么要使用一种将您限制为一个连接的设计,而不是创建类的实例然后让该实例存储套接字,但考虑到您倾向于只为一个连接设计,您可以像上面一样将其设为模块级变量。

【讨论】:

  • 感谢您的评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-10
  • 1970-01-01
  • 1970-01-01
  • 2012-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多