Websockets无法正常工作

我在javascript中有以下代码:

function ConnectWebSocket() { if ("WebSocket" in window) { myWebsocket = new WebSocket("wss://myserver/mychannel"); myWebsocket.onmessage = function(evt) { alert("onmessage"); } myWebsocket.onopen = function() { alert("onopen"); myWebsocket.send("msg0"); myWebsocket.send("msg1"); myWebsocket.send("msg2"); } myWebsocket.onclose = function() { alert("onclose"); ConnectWebSocket(); } } else { // Do something if there is no websockets support } } ConnectWebSocket(); 

问题是在Firefox中,连接在发送消息后关闭,并由于onclose事件上的命令而重新打开。 如果我尝试在onopen上只发送一条消息,则连接保持打开状态,但如果我尝试发送多条消息,则连接将关闭。 此问题仅出现在Firefox中,而不是在Chrome中,而不是在IE中,而不是在Safari中。

有人能帮我吗? 在IE或Chrome等其他浏览器中,一旦创建了连接,它就会一直打开,直到我离开页面。 我有40.0.3v的Firefox

试试这个例子:

 var url = "ws://echo.websocket.org"; if (!window.WebSocket) alert("WebSocket not supported by this browser"); var myWebSocket = { connect: function () { var location = url this._ws = new WebSocket(location); this._ws.onopen = this._onopen; this._ws.onmessage = this._onmessage; this._ws.onclose = this._onclose; this._ws.onerror = this._onerror; }, _onopen: function () { console.debug("WebSocket Connected"); }, _onmessage: function (message) { console.debug("Message Recieved: " + message.data); }, _onclose: function () { console.debug("WebSocket Closed"); kiosk.connect(); }, _onerror: function (e) { console.debug("Error occured: " + e); }, _send: function (message) { console.debug("Message Send: " + message); if (this._ws) this._ws.send(message); } }; myWebSocket.connect(); setInterval(function() { myWebSocket._send('msg1'); }, 5000); 

这是一个JSFidlle

可能是您的support var没有按预期运行。 以下代码在FireFox中无需关闭连接:

 function ConnectWebSocket() { if ("WebSocket" in window) { myWebsocket = new WebSocket("ws://echo.websocket.org/"); myWebsocket.onmessage = function (evt) { alert("onmessage"); } myWebsocket.onopen = function () { alert("onopen"); myWebsocket.send("a test message"); } myWebsocket.onclose = function () { alert("onclose"); ConnectWebSocket(); } } else { // Do something if there is no websockets support } } ConnectWebSocket(); 

示例小提琴


  • 您可以使用Websocket.org上的工具确保websockets在浏览器中正常工作。
  • 或者(尽管您的问题是使用FF),您可以使用此处列出的步骤来调试websockets。

试试吧。

  var WS = window.WebSocket || window.MozWebSocket;; if (WS){ var websocket = new WS("wss://myserver/mychannel"); }