Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  193] [ 6]  / answers: 1 / hits: 22530  / 12 Years ago, thu, november 29, 2012, 12:00:00

In Firefox (at least), if you hit ESC, then it will close all open WebSockets connections.
I need to capture that disconnection and try to re-connect once it's available again.



Here's an example of the code I've tried to implement, but nothing I can figure out will catch the error and allow me to handle it gracefully.



Have a look at the code: http://jsfiddle.net/w5aAK/



var url = ws://echo.websocket.org;
try {
socket = window['MozWebSocket'] ? new MozWebSocket(url) : new WebSocket(url);
socket.onopen = function(){
console.log('Socket is now open.');
};
socket.onerror = function (error) {
console.error('There was an un-identified Web Socket error');
};
socket.onmessage = function (message) {
console.info(Message: %o, message.data);
};
} catch (e) {
console.error('Sorry, the web socket at %s is un-available', url);
}

setTimeout(function(){
socket.send(Hello World);
}, 1000);


Turn on your console and watch the output.



Am I doing something wrong here, or is it just not possible because the connection is running outside of the scope of the JS script?



Any input would be helpful.



Thanks!


More From » websocket

 Answers
68

You can attach a handler to the socket.onclose event. It will be called when you hit ESC and the connection is interrupted.



See: http://jsfiddle.net/w5aAK/1/



One problem that you can't get around at the moment is the interrupted error being output to the console. There's no way of capturing that at the moment I'm afraid.


[#81733] Wednesday, November 28, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sidneyh

Total Points: 118
Total Questions: 108
Total Answers: 105

Location: Mali
Member since Fri, Jun 18, 2021
3 Years ago
sidneyh questions
Tue, Jun 7, 22, 00:00, 2 Years ago
Wed, Apr 13, 22, 00:00, 2 Years ago
Wed, Aug 12, 20, 00:00, 4 Years ago
Wed, Jun 3, 20, 00:00, 4 Years ago
Fri, Apr 24, 20, 00:00, 4 Years ago
;