var WebSocketHandler = function(terminal, uri) { this.terminal = terminal; this.uri = uri; this.webSocket = new WebSocket(uri); var self = this; this.onOpen = function(e) { self.terminal.ui.println('Connected to ' + self.uri, self.INFO_COLOR); }; this.onClose = function(e) { self.terminal.ui.println('Disconnected from ' + self.uri, self.INFO_COLOR); }; this.onMessage = function(e) { var packet = JSON.parse(e.data); var id = packet.id; if (id == null) { self.terminal.ui.println('ID is null', self.FAILURE_COLOR); return; } var callback = self.terminal.callbacks[id.toString()]; delete self.terminal.callbacks[id.toString()]; var args = self.terminal.args[id.toString()]; delete self.terminal.args[id.toString()]; if (callback == null) { self.terminal.ui.println('Callback is null for ID ' + id, self.FAILURE_COLOR); return; } callback(packet, args); }; this.onError = function(e) { self.terminal.ui.println('Error on ' + self.uri, self.INFO_COLOR); }; this.webSocket.onopen = this.onOpen; this.webSocket.onclose = this.onClose; this.webSocket.onmessage = this.onMessage; this.webSocket.onerror = this.onError; }; WebSocketHandler.prototype.INFO_COLOR = '#a080a0'; WebSocketHandler.prototype.SUCCESS_COLOR = '#4080c0'; WebSocketHandler.prototype.FAILURE_COLOR = '#f06040';