Changeset 59

Show
Ignore:
Timestamp:
04/12/06 14:14:08 (2 years ago)
Author:
Jan-Klaas Kollhof
Message:

additional JSON-RPC impl. for sockets and some sockets modification

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/jsolait/lib/jsonrpc.js

    r44 r59  
    3030    /** 
    3131        Thrown if a  server did not respond with response status 200 (OK). 
    32     *
     32    **
    3333    mod.InvalidServerResponse = Class(mod.Exception, function(publ, supr){ 
    3434        /** 
    3535            Initializes the Exception. 
    3636            @param status       The status returned by the server. 
    37         *
     37        **
    3838        publ.__init__= function(status){ 
    3939            supr.__init__.call(this, "The server did not respond with a status 200 (OK) but with: " + status); 
     
    4646    /** 
    4747        Thrown if an JSON-RPC response is not well formed. 
    48     *
     48    **
    4949    mod.MalformedJSONRpc = Class(mod.Exception, function(publ, supr){ 
    5050        /** 
     
    5353            @param json           The json source. 
    5454            @param trace=undefined  The error causing this Exception 
    55         *
     55        **
    5656        publ.__init__= function(msg, s, trace){ 
    5757            supr.__init__.call(this, msg,trace); 
     
    6363    /** 
    6464        Thrown if an JSON-RPC error is returned. 
    65     *
     65    **
    6666    mod.JSONRPCError = Class(mod.Exception, function(publ, supr){ 
    6767        /** 
     
    6969            @param err          The error object. 
    7070            @param trace=undefined  The error causing this Exception 
    71         *
     71        **
    7272        publ.__init__= function(err, trace){ 
    7373            supr.__init__.call(this, err,trace); 
     
    8383        @param obj    The object to marshall 
    8484        @return         An xml representation of the object. 
    85     *
     85    **
    8686    mod.marshall = function(obj){ 
    8787        if(obj == null){ 
     
    104104        @param source    The source  to unmarshall. 
    105105        @return         The JavaScript object created. 
    106     *
     106    **
    107107    mod.unmarshall = function(source){ 
    108108        try { 
     
    124124        then the remote method will be called asynchronously. 
    125125        The results and errors are passed to the callback. 
    126     *
     126    **
    127127    mod.JSONRPCMethod =Class(function(publ){ 
    128128 
     
    173173            @param user=null             The user name to use for HTTP authentication. 
    174174            @param pass=null             The password to use for HTTP authentication. 
    175         *
     175        **
    176176        publ.__init__ = function(url, methodName, user, pass){ 
    177177            this.methodName = methodName; 
     
    215215            @param user    The user name. 
    216216            @param pass    The password. 
    217         *
     217        **
    218218        publ.setAuthentication = function(user, pass){ 
    219219            this.user = user; 
     
    224224            Sends the call as a notification which does not have a response. 
    225225            Call this as if you would call the method itself. Callbacks are ignored. 
    226         *
     226        **
    227227        publ.notify = function(){ 
    228228            var args=new Array(); 
     
    247247        Creates proxy objects which resemble the remote service. 
    248248        Method calls of this proxy will result in calls to the service. 
    249     *
     249    **
    250250    mod.ServiceProxy=Class(function(publ){ 
    251251        /** 
     
    260260            @param user=null             The user name to use for HTTP authentication. 
    261261            @param pass=null             The password to use for HTTP authentication. 
    262         *
     262        **
    263263        publ.__init__ = function(url, methodNames, user, pass){ 
    264264            this._url = url; 
     
    271271            Adds new JSONRPCMethods to the proxy server which can then be invoked. 
    272272            @param methodNames   Array of names of methods that can be called on the server. 
    273         *
     273        **
    274274        publ._addMethodNames = function(methodNames){ 
    275275            for(var i=0;i<methodNames.length;i++){ 
     
    300300            @param user    The user name. 
    301301            @param pass    The password. 
    302         *
     302        **
    303303        publ._setAuthentication = function(user, pass){ 
    304304            this._user = user; 
     
    318318        publ._methods=new Array(); 
    319319    }); 
    320  
    321      
    322  
    323     mod.NotificationReceiver = Class(function(publ,supr){ 
    324          publ.__init__ = function(url){ 
    325             this._url = url; 
    326             var req = new XMLHttpRequest(); 
    327             req.multipart = true; 
    328             var self = this; 
    329             req.open('POST', url, true); 
    330             req.onload = function(evt){ 
    331                 self._handleData(evt.target.responseText); 
    332             }; 
    333             req.send(''); 
    334         }; 
    335          
    336          
    337         publ._handleData = function(data){ 
    338             var f = new Function('','return ' + data); 
    339             var o = f(); 
    340             if(this[o.method]){ 
    341                 this[o.method].apply(this, o.params); 
    342             } 
    343          }; 
    344     }); 
    345      
    346      
    347     mod.HTTPConnection=Class(function(publ,supr){ 
    348         publ.__init__=function(url, datahandler){ 
    349             this.url = url; 
    350             this.datahandler = datahandler; 
    351         }; 
    352          
    353         publ.send = function(data){ 
    354             var datahandler = this.datahandler; 
    355             urllib.postURL(this.url, data, function(req){ 
    356                 datahandler(req.responseText); 
    357             }); 
    358         }; 
    359     }); 
    360      
    361     mod.ContinousHTTPConnection=Class(function(publ,supr){ 
    362          
     320         
     321    mod.SimpleHTTPConnection=Class(function(publ,supr){ 
    363322         publ.__init__=function(url, datahandler){ 
    364323            this.url = url; 
    365324            this.datahandler = datahandler; 
    366             this.queue=[]; 
    367             this.isWaitingForResponse=false; 
    368             this.isWaitingForServer=false; 
    369             this.processQueue(); 
    370325        }; 
    371326         
    372327        publ.send = function(data){ 
    373             this.queue.push(data); 
    374             this.processQueue(); 
    375         }; 
    376          
    377         publ.waitForServer=function(){ 
    378             this.isWaitingForServer=true; 
    379             var self=this; 
    380             this.currentRequest= urllib.postURL(this.url, "", function(req){ 
    381                 self.isWaitingForServer=false; 
    382                 self.processData(req.responseText); 
    383             }); 
     328            urllib.postURL(this.url, data, bind(this, function(req){ 
     329                this.processData(req.responseText); 
     330            })); 
    384331        }; 
    385332         
     
    388335                this.datahandler(data); 
    389336            } 
    390             this.processQueue(); 
    391         }; 
    392                  
    393         publ.sendAndWaitResponse=function(data){ 
    394             this.isWaitingForResponse=true; 
    395             var self = this; 
    396             this.currReq = urllib.postURL(this.url, data, function(req){ 
    397                 self.isWaitingForResponse = false; 
    398                 self.processData(req.responseText); 
    399             }); 
    400         }; 
    401          
    402         publ.processQueue = function(){ 
    403             if((this.queue.length > 0) && (! this.isWaitingForResponse)){ 
    404                 var data =this.queue.join(""); 
    405                 this.queue=[]; 
    406                 this.sendAndWaitResponse(data);             
    407             } 
    408              
    409             if((! this.isWaitingForServer) && (! this.isWaitingForResponse)){ 
    410                 this.waitForServer(); 
    411             } 
     337        }; 
     338    }); 
     339     
     340    mod.SocketConnection = Class(function(publ,priv,supr){ 
     341        publ.__init__=function(host, port, datahandler){ 
     342            this.host = host; 
     343            this.port = port; 
     344            this.datahandler = datahandler; 
     345            this.socket = imprt('net.sockets').createSocket(); 
     346            this.socket.onData = function(data){ 
     347                datahandler(data); 
     348            }; 
     349            this.socket.connect(host, port); 
     350        }; 
     351         
     352        publ.send = function(data){ 
     353            this.socket.send(data); 
    412354        }; 
    413355    }); 
     
    415357    mod.RPCMethod=Class(function(publ,supr){ 
    416358        publ.__init__=function(name,proxy){ 
    417             this.name = name; 
     359            this._name = name; 
    418360            this.proxy = proxy; 
    419361        }; 
     
    426368            if(typeof args[args.length-1] == "function"){ 
    427369                var callback = args.pop(); 
    428                 return this.proxy._sendRequest(this.name, args, callback); 
     370                return this.proxy._sendRequest(this._name, args, callback); 
    429371            }else{ 
    430                 return this.proxy._sendNotification(this.name, args); 
     372                return this.proxy._sendNotification(this._name, args); 
    431373            } 
    432374        }; 
     
    435377    mod.ServiceProxy2=Class(function(publ,supr){ 
    436378        publ.__init__ = function(serviceurl, methodNames, localService){ 
    437             this._url = serviceurl;             
    438             var c = new mod.ContinousHTTPConnection(this._url, bind(this, this._handleData)); 
     379            this._url = serviceurl;     
     380 
     381            if(serviceurl.slice(0,10) == "jsonrpc://"){ 
     382                var hostport = serviceurl.slice(10).split(":"); 
     383                hostport.push(5766);//default json-rpc port 
     384                var host =hostport.shift(); 
     385                var port = hostport.shift(); 
     386                this._connection = new mod.SocketConnection(host, port, bind(this, this._handleData)); 
     387            }else{ 
     388                this._connection = new mod.SimpleHTTPConnection(this._url, bind(this, this._handleData)); 
     389            } 
    439390            this._attachMethods(methodNames); 
    440391            this._localService = localService == null ? {}:localService; 
     
    445396            Adds new JSONRPCMethods to the proxy server which can then be invoked. 
    446397            @param methodNames   Array of names of methods that can be called on the server. 
    447         *
     398        **
    448399        publ._attachMethods = function(methodNames){ 
    449400            for(var i=0;i<methodNames.length;i++){ 
     
    470421         
    471422        publ._handleData = function(data){ 
    472             var d = 'return [' + data.replace(/\0/g, ",") + ']'; 
     423            var d = 'return [' + data.replace(/\n/g, ",") + ']'; 
    473424            try{ 
    474425                f=new Function('',d); 
     
    482433                    this._handleInvokation(messages[i].method, messages[i].params, messages[i].id); 
    483434                }else if(messages[i].method != null  && messages[i].params != null && messages[i].id == null){ 
    484                     this._handleNotification(messages[i].result, messages[i].error); 
     435                    this._handleNotification(messages[i].method, messages[i].params); 
    485436                }else if(messages[i].id != null){ 
    486437                    this._handleResponse(messages[i].result, messages[i].error, messages[i].id); 
     
    502453            if(this._localService[method]){ 
    503454                var rslt = this._localService[method].apply(this._localService, params); 
    504                 if(isinstanceof(rslt, mod.DelayedResponse)){ 
    505                     rslt.id=id; 
    506                 }else{ 
    507                     this._sendResponse(rslt, null, id); 
    508                 } 
     455                this._sendResponse(rslt, null, id); 
    509456            }else{ 
    510457                this._sendResponse(null, "Method Not Found", id); 
     
    518465        }; 
    519466         
    520         publ._sendData = function(data){ 
    521             print(data); 
     467        publ._sendMessage = function(data){ 
     468            this._connection.send(data + "\n"); 
    522469        }; 
    523470         
    524471        publ._sendRequest=function(method, params, callback){ 
    525             var r = new PendingRequest(callback); 
     472            var r = new mod.PendingRequest(callback); 
    526473            this._pendingRequests[hash(r)] = r; 
    527474            var data = mod.marshall({method:method, params:params, id:hash(r)}); 
    528             this._sendData(data); 
     475            this._sendMessage(data); 
    529476            return r; 
    530477        }; 
     
    532479        publ._sendNotification=function(method, params){ 
    533480            var data = mod.marshall({method:method, params:params, id:null}); 
    534             this._sendData(data); 
     481            this._sendMessage(data); 
    535482        }; 
    536483         
    537484        publ._sendResponse=function(result, error, id){ 
    538485            var data = mod.marshall({result:result, error:error, id:id}); 
    539             this._sendData(data); 
    540         }; 
    541          
    542     }); 
    543      
    544     var PendingRequest=Class(function(publ,supr){ 
     486            this._sendMessage(data); 
     487        }; 
     488         
     489    }); 
     490     
     491    mod.PendingRequest=Class(function(publ,supr){ 
    545492        publ.__init__=function(callback){ 
    546493            this.callback=callback; 
     
    555502    /** 
    556503        Converts a String to JSON. 
    557     *
     504    **
    558505    String.prototype.toJSON = function(){ 
    559506        var s = '"' + this.replace(/(["\\])/g, '\\$1') + '"'; 
     
    564511    /** 
    565512        Converts a Number to JSON. 
    566     *
     513    **
    567514    Number.prototype.toJSON = function(){ 
    568515        return this.toString(); 
     
    571518    /** 
    572519        Converts a Boolean to JSON. 
    573     *
     520    **
    574521    Boolean.prototype.toJSON = function(){ 
    575522        return this.toString(); 
     
    579526        Converts a Date to JSON. 
    580527        Date representation is not defined in JSON. 
    581     *
     528    **
    582529    Date.prototype.toJSON= function(){ 
    583530        var padd=function(s, p){ 
     
    599546    /** 
    600547        Converts an Array to JSON. 
    601     *
     548    **
    602549    Array.prototype.toJSON = function(){ 
    603550        var v = []; 
     
    607554        return "[" + v.join(", ") + "]"; 
    608555    }; 
    609  
     556     
    610557    mod.__main__ = function(){ 
    611         
    612     
    613         print("creating ServiceProxy object using introspection for method construction...\n"); 
    614         var s = new mod.ServiceProxy("http://jsolait.net/testj.py",["echo"]); 
    615         print("%s created\n".format(s)); 
    616         print("creating and marshalling test data:\n"); 
    617         var o = [1.234, 5, {a:"Hello ' \" World", b:new Date()}]; 
    618         print(mod.marshall(o)); 
    619         print("\ncalling echo() on remote service...\n"); 
    620         var r = s.echo(o); 
    621         print("service returned data(marshalled again):\n"); 
    622         print(mod.marshall(r)); 
    623558    }; 
    624559}); 
  • trunk/jsolait/lib/net/sockets.js

    r44 r59  
    6161    mod.FlashSocket=Class(mod.Socket, function(publ,priv,supr){ 
    6262         
    63         publ.__init__=function(){ 
    64             this.id = flashSocketProvider.newSocket(); 
    65             flashSocketWrappers[this.id] = this; 
    66         }; 
    67          
    6863        publ.connect=function(host, port){ 
     64            if(this.id != null){ 
     65                this.close(); 
     66            }else{ 
     67                this.id = flashSocketProvider.newSocket(); 
     68                flashSocketWrappers[this.id] = this; 
     69            } 
    6970            flashSocketProvider.connect(this.id, host, port); 
    7071        }; 
    7172         
    7273        publ.send=function(data){ 
    73             flashSocketProvider.send(this.id, data); 
     74            if(this.id != null){ 
     75                flashSocketProvider.send(this.id, data); 
     76            }else{ 
     77                throw new mod.Exception("Socket not connected"); 
     78            } 
    7479        }; 
    7580         
    7681        publ.close=function(){ 
    7782            flashSocketProvider.close(this.id); 
     83            delete this['id']; 
    7884        }; 
    7985    }); 
    8086     
    8187     
    82     var ie= '<object  id="__SocketProvider__"  classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"  style="visibility:hidden;display:none;" width="0" height="0" ><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="%s" /></object>'; 
    83     var moz = '<embed name="__SocketProvider__" src="./SocketProvider.swf" width="100" height="30"  allowScriptAccess="sameDomain" type="application/x-shockwave-flash" />'; 
     88    var ie= '<object  id="__SocketProvider__"  classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"  style="visibility:hidden;" width="0" height="0" ><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="%s" /></object>'; 
     89    var moz = '<embed id="__SocketProvider__" src="%s" width="100" height="30"  allowScriptAccess="sameDomain" type="application/x-shockwave-flash" />'; 
    8490     
    8591    var addFlashToPage=function(){ 
     
    9298            d.setAttribute("width", "0"); 
    9399            d.setAttribute("height", "0"); 
    94             d.setAttribute("style", "visibility:hidden;display:none;"); 
     100            d.setAttribute("style", "visibility:hidden;"); 
    95101            d.setAttribute( "type","application/x-shockwave-flash"); 
     102            d.setAttribute( "allowScriptAccess","sameDomain"); 
     103            d.setAttribute( "id","__SocketProvider__"); 
    96104            document.documentElement.appendChild(d); 
    97105            flashSocketProvider=d; 
     
    114122        } 
    115123    }; 
    116  
     124     
     125    
     126     
    117127    mod.isReady = function(){ 
    118128        return flashSocketProvider != null;