0

我有一个连接问题,我有一个快速服务器并创建一个ws传递快速服务器实例的实例,当我连接时,连接成功并尝试发送一条消息我可以收到一次消息,当我关闭连接并连接时然后再发送一条消息,消息现在发送两次,每次继续这样做,消息保持加倍,我在通道上的套接字只是一个连接,我认为它创建了一个新的过程?我怎样才能防止这种行为?

/**
	 * New WebScoket instance initialize
	 * @type WebSocket
	 */
	const ws = new WebSocket.Server({ /*verifyClient,*/ server });
	console.log('instantiate');
	const rooms = {};

/**
	 * Add new collection
	 * @param {String} room
	 * @param {String} channel
	 * @param {Object} socket
	 * @returns {Undefined|Null}
	 */
	function add(room, channel, socket) 
	{
		if(typeof rooms[room] == 'undefined') rooms[room] = {};
		if(typeof rooms[room][channel] == 'undefined') rooms[room][channel] = [];
		if(typeof rooms[room][channel] != 'undefined') rooms[room][channel].push(socket);
		redis.subscribe(`${room}-${channel}`);
		return;
	}

	/**
	 * Add new properties to socket
	 * @param {String} room
	 * @param {String} channel
	 * @return {Object}
	 */
	function addPropToSocket(room, channel)
	{
		return {room, channel};
	}

	/**
	 * Send message to user
	 * @param  {String} room
	 * @param  {String} channel
	 * @param  {String} msg
	 * @param  {Object} socket
	 * @return {void}
	 */
	function send(room, channel, msg, socket)
	{
		if(typeof rooms[room] == 'undefined') return;
		if(typeof rooms[room][channel] == 'undefined') return;
		rooms[room][channel].forEach(user => {
			// if(user !== socket && user.readyState === WebSocket.OPEN) user.send(msg);
			if(user.readyState === WebSocket.OPEN) user.send(msg);
		});
	}

	/**
	 * Remove user from room
	 * @param  {String} room
	 * @param  {String} channel
	 * @param  {Object} socket
	 * @return {void}
	 */
	function rm(room, channel, socket)
	{
		if(typeof rooms[room] == 'undefined') return;
		if(typeof rooms[room][channel] == 'undefined') return;
		rooms[room][channel] = rooms[room][channel].filter(user => user != socket);
		// redis.unsubscribe(`${room}-${channel}`);
	}

//@Connection socket connection event
	ws.on('connection', function connection(socket, req) {
		socket.isActive = true;
		const f = formatSocketUrl(req.url);
		socket['props'] = addPropToSocket(...f);
		add(...f, socket);
		socket.on('message', msg => send(...f, msg, socket));
		socket.on('pong', () => socket.isActive = true);
		socket.on('close', () => {
			rm(socket.props.room, socket.props.channel, socket);
		});
		redis.on('message', (channel , msg) => {
			const f = channel.split('-');
			send(...f, msg, socket);
		});
	});

4

0 回答 0