I’m encountering an intermittent issue with a WebSocket connection in my Node.js application. The WebSocket connection is managed within a function called connectWebSocket, which establishes a connection using the ws library. This function is utilized concurrently by two processes .
The connectWebSocket function performs several tasks:
- It initializes a WebSocket instance with specific headers.
- It waits for the WebSocket connection to open and handles events like ‘close’ and ‘error’.
- It processes chunks of data from a tokenList using another function called processChunk.
- Finally, it closes the WebSocket connection.
Here’s the function code :
async function connectWebSocket(scriptIdentifier, tokenList) {
console.log('inside the webscoket funtion 11111111111111111111111111111')
const ws = new WebSocket('wss://xyz', {
headers: {
'x-api-key': process.env.API_KEY,
'x-client-code': process.env.CLIENT_CODE,
'x-feed-token': feedToken
}
});
console.log('2222222222222222222222222222222', feedToken)
await new Promise((resolve, reject) => {
console.log('2.5 2.5 +++++++++++++++inside await block');
ws.on('open', function open() {
console.log('inside the webscoket open 33333333333333333333333333333333')
resolve();
});
ws.on('close', function close() {
console.log('Disconnected from WebSocket server');
resolve();
});
ws.on('error', (err) => {
console.log(err);
reject();
});
});
console.log('444444444444444444444444')
const chunks = [];
for (let i = 0; i < tokenList.length; i += 999) {
chunks.push(tokenList.slice(i, i + 999));
}
await chunks.reduce((prevPromise, chunk) => {
return prevPromise.then(() => {
console.log('55555555555555555555555555555')
return processChunk(scriptIdentifier, ws, chunk)
})
}, Promise.resolve())
ws.close()
}
The function sometimes hangs indefinitely around the following line:
console.log('2.5 2.5 +++++++++++++++inside await block');
At this point, the function neither progresses nor throws any errors, leading to a halt in the execution flow. This problem occurs sporadically and does not consistently trigger, making it challenging to pinpoint the root cause.
Adding to the context, the concurrent processes are running on PM2. These processes utilise the Web Socket functionality provided by the connectWebSocket function to exchange data.