Solve the problem of error reporting when socket.io uses disconnect in express framework

When I used express to create other functions in the chat room today, I found that an io.emit('disconnect') method reported an error . The error message is as follows:

 throw new Error(`"${
      
      String(ev)}" is a reserved event name`);
            ^

Error: "disconnect" is a reserved event name
    at BroadcastOperator.emit (D:\expressframe\myexpressjsj\node_modules\socket.io\dist\broadcast-operator.js:159:19)
    at Namespace.emit (D:\expressframe\myexpressjsj\node_modules\socket.io\dist\namespace.js:307:73)
    at Server.<computed> [as emit] (D:\expressframe\myexpressjsj\node_modules\socket.io\dist\index.js:806:33)
    at Socket.<anonymous> (D:\expressframe\myexpressjsj\scoketio:19:16)
    at Socket.emit (node:events:390:28)
    at Socket.emitReserved (D:\expressframe\myexpressjsj\node_modules\socket.io\dist\typed-events.js:56:22)
    at Socket._onclose (D:\expressframe\myexpressjsj\node_modules\socket.io\dist\socket.js:561:14)
    at Client.onclose (D:\expressframe\myexpressjsj\node_modules\socket.io\dist\client.js:247:20)
    at Socket.emit (node:events:402:35)
    at Socket.onClose (D:\expressframe\myexpressjsj\node_modules\engine.io\build\socket.js:310:18)

What does this mean? It probably means that a reserved word is used. Then check that the first error is reported when emit uses disconnect. Because I defined a disconnect method on the front end to broadcast the user's exit information, so I When the terminal monitors disconnect, it not only needs to report messages in the background, but also uses the io.emit() method to trigger their respective disconnect methods to all socket users, but an error is actually reported! So after checking the official website, it probably means that disconnect can use socket.on to monitor in the background, but it cannot be used in emit, so that's a good solution! We cannot use emit to trigger the disconnect method, so when we define this method on the front end, we can just change the name disconnect, so I changed it to logout, which means log out, and then modify the content of emit in the back end. Problem.
rear end

socket.on('disconnect',function()
        {
    
    
            console.log(socket.userid+'已经退出聊天室');
            io.emit('logout',socket.userid)
        })

front end

this.socket.on('logout',function(userid)
        {
    
    
            console.log(userid+'退出聊天室!');
        })

No problem, just introduce it below:
Insert image description here
Browser
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_51295863/article/details/131674975