I have a problem on connection , I have a express server and create a ws
instance passing the express server instance , when I connect, the connection was successful and try to send a message I can receive message once, and when I close the connection and connect again then send a message the message now send twice , and every time a keep doing this the message keeping doubled, my socket on a channel is just only one connection , I think its creating a new proccess ? How can I prevent this behavior ?
/**
* 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);
});
});