socket.io connect and disconnect

1. Server

Listen to the connection event

io.sockets.on('connection', (socket) => {
    
    
    console.log("connection socket:", socket.handshake.query.username)
	
	// 监听断开事件
	socket.on('disconnect', (reason) => {
    
    
            console.log("disconnect reason ", reason)
            //userMap.delete(socket.handshake.query.username)
    })
}

Here you can view some request parameters through socket.handshake.query, make some restrictions on the connection, and reject those that do not meet the conditions

2. Client

var username = document.querySelector('input#username')
// connect
socket = io.connect('', {
    
     query: "username=" + username.value });

// 30 秒后主动断开连接
setTimeout(function () {
    
    
        socket.disconnect()
    }, 30000)

io.connect interface, the first parameter is the request url, and the second parameter is related parameters, here carries the user name

Guess you like

Origin blog.csdn.net/zjoops1314/article/details/126652737