javascript 我可以捕获失败的 websocket 连接的“无法建立连接”错误吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22919638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I catch the "can't establish a connection" error for a failed websocket connection?
提问by semmelbroesel
I need to test if the connection to my websocket server is established or not.
我需要测试与我的 websocket 服务器的连接是否建立。
At this time, I CAN connect to the server, but I want to be able to catch the possibility of that server not being reachable, so this question is about what to do when the websocket connection cannot be established or when it times out.
这个时候可以连接到服务器,但是我希望能够捕捉到那个服务器不可达的可能性,所以这个问题是关于当websocket连接无法建立或超时时该怎么办。
Using just the basic websocket code in Firefox, it will timeout in about 20 seconds and call my error handler. But it will also throw a JavaScript error that (at least for me using Firebug) shows up in the browser. The log then shows:
在 Firefox 中只使用基本的 websocket 代码,它会在大约 20 秒后超时并调用我的错误处理程序。但它也会抛出一个 JavaScript 错误(至少对我使用 Firebug 来说)显示在浏览器中。然后日志显示:
Firefox can't establish a connection to the server at ws://192.168.0.1/.
What I've tried so far:
到目前为止我尝试过的:
- Prevent the 20 second timeout by adding my own
window.timeout
that checks if theonopen
handler has been called yet or not, but that does not prevent the JavaScript error. Force-close the websocket at the end of my own timeout, but now I get TWO JavaScript errors - the original plus:
The connection to ws://192.168.0.1/ was interrupted while the page was loading.
Adding
try {} catch(e) {}
to my code, both when connecting the socket and closing it - no change.
- 通过添加我自己的
window.timeout
检查onopen
处理程序是否已被调用来防止 20 秒超时,但这并不能防止 JavaScript 错误。 在我自己的超时结束时强制关闭 websocket,但现在我收到两个 JavaScript 错误 - 原来的加号:
The connection to ws://192.168.0.1/ was interrupted while the page was loading.
添加
try {} catch(e) {}
到我的代码中,在连接套接字和关闭它时都没有变化。
Any ideas on how to get websocket errors to not show in the browser?
关于如何让 websocket 错误不显示在浏览器中的任何想法?
采纳答案by DerDu
What i've learnd so far is: you cant :0(
到目前为止我学到的是:你不能:0(
... because this is somewhat browser specific behavior...
...因为这在某种程度上是浏览器特定的行为...
- so the only thing you can do is using callbacks on ws object and pray ...
- ORjust overwrite
console.log
;0)
- 所以你唯一能做的就是在 ws 对象上使用回调并祈祷......
- 或者只是覆盖
console.log
;0)
with the code i did however i got rid of some error messages, maybe it'll help ;)
使用我所做的代码但是我摆脱了一些错误消息,也许它会有所帮助;)
e.g:
例如:
- Chrome won't complain about dead servers and silently try to reconnect..
- IE 11 still gives script error
- etc..
- Chrome 不会抱怨服务器死机并默默地尝试重新连接..
- IE 11 仍然出现脚本错误
- 等等..
A Basic Class to wrap WS : Have a look at callbacks !
包装 WS 的基本类:看看回调!
/**
* Socket Class
*/
Client.Source.Network.Socket.Class = new Class({ implements: [Client.Source.Network.Socket.Interface] },function( Host, Port ){
var Configuration = {
Server: {
Protocol: 'ws',
Host: Host,
Port: Port
},
Event: {
Open: function(){},
Error: function(){},
Message: function(){},
Close: function(){}
}
};
var Socket = null;
/**
* @return {string}
*/
var HostUrl = function() {
return Configuration.Server.Protocol + '://' + Configuration.Server.Host + ':' + Configuration.Server.Port + '/Connection'
};
/**
* @returns {boolean}
*/
var IsSupported = function() {
return "WebSocket" in window;
};
this.Open = function() {
if( IsSupported() ) {
Socket = new WebSocket( HostUrl() );
Socket.onopen = Configuration.Event.Open;
Socket.onerror = Configuration.Event.Error;
Socket.onmessage = Configuration.Event.Message;
Socket.onclose = Configuration.Event.Close;
} else {
}
};
this.Send = function( Text ) {
Socket.send( Text );
};
this.Close = function() {
Socket.close();
};
this.onOpen = function( Callback ) {
Configuration.Event.Open = Callback;
};
this.onError = function( Callback ) {
Configuration.Event.Error = Callback;
};
this.onMessage = function( Callback ) {
Configuration.Event.Message = Callback;
};
this.onClose = function( Callback ) {
Configuration.Event.Close = Callback;
};
});
Have a look at the Connect() : onError(), onClose() function
看看 Connect() : onError(), onClose() 函数
/**
* Network Class
*/
Client.Source.Network.Class = new Class({ implements: [Client.Source.Network.Interface] },function(){
var _Self = this;
var Socket = null;
this.Connect = function( Host, Port ) {
Socket = new Client.Source.Network.Socket.Class( Host, Port );
Socket.onOpen(function(){
_Self.Gui().Create( Client.Module.Client.Gui() );
Client.Module.Chat.Message('Connected', 'green', 11);
Client.Module.Audio.Play( 'Client.Resource.Audio.Chat.UserOnline', 0.2 );
});
Socket.onMessage( Response );
Socket.onError(function(){
Client.Module.Chat.Message('Connection Error', 'red', 11);
});
Socket.onClose(function(){
_Self.Gui().Destroy();
Client.Module.Chat.Message('Disconnected', 'darkred', 11);
Client.Module.Chat.Message('Connecting...', 'orange', 11);
window.setTimeout(function () {
_Self.Connect( Host, Port );
}, 2000);
});
Socket.Open();
};
this.Request = function( Application, Request, Data ) {
Socket.Send( JSON.stringify( { Application: Application, Request: Request, Data: Data } ) );
};
var Response = function( Message ) {
Message = JSON.parse( Message.data );
Library[Message.Application].Execute( Message.Request, Message.Data );
};
var Library = {};
this.Protocol = function( Application, Callback ) {
Library[Application] = Callback;
};
var GuiObject = null;
this.Gui = function Gui() {
if( GuiObject === null ) {
GuiObject = new Client.Source.Network.Gui();
}
return GuiObject;
};
});