1 /* -----------------------------------------------------------------------
2 * Copyright (C) 2012 Equinox Software, Inc.
3 * Bill Erickson <berick@esilibrary.com>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * ----------------------------------------------------------------------- */
16 var WS_PATH = '/osrf-websocket';
19 * onopen is required. no data can be sent
20 * until the async connection dance completes.
22 OpenSRF.WSRequest = function(session, args, onopen) {
23 this.session = session;
26 var proto = location.protocol == 'https' ? 'wss' : 'ws';
28 var path = proto + '://' + location.host +
29 WS_PATH + '?service=' + this.session.service;
32 this.ws = new WebSocket(path);
34 throw new Error("WebSocket() not supported in this browser " + e);
39 this.ws.onopen = function(evt) {
43 this.ws.onmessage = function(evt) {
44 self.core_handler(evt.data);
47 this.ws.onerror = function(evt) {
48 self.transport_error_handler(evt.data);
51 this.ws.onclose = function(evt) {
55 OpenSRF.WSRequest.prototype.send = function(message) {
56 //console.log('sending: ' + js2JSON([message.serialize()]));
57 this.last_message = message;
58 this.ws.send(js2JSON([message.serialize()]));
62 OpenSRF.WSRequest.prototype.close = function() {
63 try { this.ws.close(); } catch(e) {}
66 OpenSRF.WSRequest.prototype.core_handler = function(json) {
67 //console.log('received: ' + json);
70 new OpenSRF.NetMessage(null, null, '', json),
72 onresponse : this.args.onresponse,
73 oncomplete : this.args.oncomplete,
74 onerror : this.args.onerror,
75 onmethoderror : this.method_error_handler()
82 OpenSRF.WSRequest.prototype.method_error_handler = function() {
84 return function(req, status, status_text) {
85 if(self.args.onmethoderror)
86 self.args.onmethoderror(req, status, status_text);
88 if(self.args.onerror) {
90 self.last_message, self.session.service, '');
95 OpenSRF.WSRequest.prototype.transport_error_handler = function(msg) {
96 if(this.args.ontransporterror) {
97 this.args.ontransporterror(msg);
99 if(this.args.onerror) {
100 this.args.onerror(msg, this.session.service, '');