- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to 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();
- Related Articles
- How to establish connection with JDBC?
- How to close the ResultSet cursor automatically, after commit in JDBC?
- How to close list items with JavaScript?
- How to fire after pressing ENTER in text input with HTML?
- How to Configure Nginx as Reverse Proxy for WebSocket
- How to close the notification panel after notification button is clicked in Android?
- How to close a Android notification after the user is clicking on it?
- Where we should close a connection in JDBC and MySQL?
- HTML DOM close() method
- How to Close Browser Tabs With a Keyboard Shortcut?
- How can I make a browser to browser (peer to peer) connection in HTML?
- How to close a browser session in Selenium with python?
- EventSource vs. wrapped WebSocket with HTML5 Server-Side Event
- Websocket for binary transfer of data & decode with HTML5
- Automatically close window after a certain time in Tkinter

Advertisements