var udid = { url: "", socket: null, connect: function (_url, _callback) { this.url = _url; var socket = this.socket; var that = this; if (socket && socket.readyState === socket.OPEN) { try { socket.send("Hi"); } catch (ex) { } return; } if (socket && socket.readyState === socket.CONNECTING) { return; } if (socket && socket.readyState === socket.CONNECTING) { try { socket.close(); } catch (e) { } finally { socket = null; } } if (socket && socket.readyState === socket.CLOSED) { socket = null; } try { socket = new WebSocket(this.url); socket.onopen = function (msg) { if (socket.readyState === socket.OPEN) socket.send("Hi"); }; socket.onmessage = function (msg) { _callback(msg.data); }; socket.onclose = function (msg) { that.close(); }; socket.onerror = function (msg) { that.close(); }; } catch (ex) { socket = null; } }, close: function () { var socket = this.socket; if (socket) { try { socket.close(); } catch (ex) { } } socket = null; } };