
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reconnect to WebSocket After Close Connection with HTML
Recreate the socket to reconnect it. The websockets are designed to stay open.
You can also go with the method to have the server close the connection. Through this, the websocket will fire an onclose event and would amazingly continue attempting to make the connection.
In addition, when the server is listening again the connection will be automatically reestablished.
Example
You can try to run the following code to reconnect to WebSocket −
// Socket Variable declaration var mySocket; const socketMessageListener = (event) => { console.log(event.data); }; // Open const socketOpenListener = (event) => { console.log('Connected'); mySocket.send('hello'); }; // Closed const socketCloseListener = (event) => { if (mySocket) { console.error('Disconnected.'); } mySocket = new WebSocket('ws://localhost:8080'); mySocket.addEventListener('open', socketOpenListener); mySocket.addEventListener('message', socketMessageListener); mySocket.addEventListener('close', socketCloseListener); }; socketCloseListener();
Advertisements