[React] Connection failure occurs when using socket.io-client in React

Article Directory

scenes to be used

When we need real-time communication, we can use WebSocket, but we already have the npm ecological chain, we can directly install the socket.io-client module, and the corresponding server uses the socket.io module.
Download and install:

// 前端
npm install socket.io-client
// 或
yarn add socket.io-client

// 后台
npm install socket.io

When we are developing the project, we may use cross-domain functions, and configure setupProxy.js accordingly

const {
    
     createProxyMiddleware } = require('http-proxy-middleware');

module.exports = app => {
    
    
    app.use('/api', createProxyMiddleware({
    
    
        target: 'http://localhost:9999',
        changeOrigin: true,
        ws: false
    }));
    app.use('/socket.io', createProxyMiddleware({
    
    
        target: 'ws://localhost:3004',
        changeOrigin: true,
        ws: true
    }));
};

Do we still need to pass in the target URL when configuring the socket?
Pro-testing is required. In addition, we'd better open an IO service to monitor socket messages, so that it will not be affected by the business port 9999.

const io = require('socket.io-client');
const socket = io('http://localhost:3004');
const app = express()
    , server = require('http').createServer(app)
    , io = require('socket.io')(server);
io.listen(3004);

module.exports = io;

Code

front end:

import store from '@store';
import {
    
     setSocketID } from '@store/actionCreators';
const Singleton = (function () {
    
    
    let instance;
    function createInstance() {
    
    
        const io = require('socket.io-client');
        const socket = io('http://localhost:3004');
        return socket;
    }

    return {
    
    
        getInstance: function () {
    
    
            if (!instance) {
    
    
                instance = createInstance().connect();
                // 创建socket就更新数据
                instance.on('connect', async () => {
    
    
                    // 更新数据库status中的socket.id
                    store.dispatch(setSocketID(instance.id));
                    await updateUS(instance.id);
                });
            }
            return instance;
        },
        disconnectSocket: ()=>{
    
    
            console.log('disconnect', instance)
            if (instance) {
    
    
                instance.disconnect();
            }
            instance = null;
            return instance;
        }
    };
})();

async function updateUS(socketID) {
    
    
    // ...
}
export default Singleton;

rear end:

const app = express()
    , server = require('http').createServer(app)
    , io = require('socket.io')(server);
io.listen(3004);

// socket
io.on('connection', function (socket) {
    
    
    console.log('连接成功')
    socket.on('newMessage', async (params) => {
    
    
    	// 。。。
        }
    });
});

module.exports = io;

Guess you like

Origin blog.csdn.net/weixin_42339197/article/details/115291297