首页 > 解决方案 > 服务器中的 Socket.io 反复断开连接,而在客户端却没有

问题描述

我打算制作一个像 WhatsApp 这样的私人聊天应用程序。我成功连接到服务器,但几秒钟后套接字与服务器断开连接。在客户端上它不会断开连接。

服务器代码:

const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = 3000;

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

const onlineusers = {};
const socketid = {};

io.on('connection', cs => {

    cs.on('online', username => {
        if(username){
            onlineusers[username] = cs.id;
            socketid[cs.id] = username;
        }

        console.log("\nonline: ", onlineusers);
    });

    cs.on('disconnect', () => {

        delete onlineusers[socketid[cs.id]];

        console.log("\noffline: ", onlineusers);
    });

});

const chat = io.of("/chat");

chat.on('connection', cs => {

    cs.on('startchat', username => {
        if (username){
            chat.to('/chat#'+onlineusers[username]).emit('hey', 'I love programming');
        }
    });

});

server.listen(port, err => {
    if(err){
        console.error("Some Error: "+err);
    }else{
        console.log(`Server is running on port: ${port}`);
    }
});

我的客户代码是由 react-native 和 socket.io-client 编写的:

在线用户文件:

import io from 'socket.io-client';
const SocketEndpoint = 'http://192.168.43.172:3000';

this.socket = io(SocketEndpoint, {
            transports: ['websocket']
        });
this.socket.on('connect', () => {

            if (this.state.username) {
                this.socket.emit("online", this.state.username);
            }

        });

 this.socket.on('connect_error', (err) => {
     Alert.alert(err);
 });

 this.socket.on('disconnect', () => {
     Alert.alert('disconnected');
 });

聊天页面文件:

import io from 'socket.io-client';
const SocketEndpoint = 'http://192.168.43.172:3000/chat';

this.socket = io(SocketEndpoint, {
                transports: ['websocket']
            });

this.socket.on('connect', () => {

            if (theirusername) {
                this.socket.emit('startchat', theirusername);
            }

            this.socket.on('hey', data => {
                alert(data);
            });

            this.socket.on('janajan', data => {
                alert(data);
            });

        });

我想保留服务器上的客户端套接字,直到客户端自己断开连接。因为在这里当我想说嘿时它会断开连接,我的消息可以传递给客户端。之前谢谢你

标签: node.jsreact-nativesocket.io

解决方案


推荐阅读