使用HPROSE 创建服务端、客户端简明教程

来源:互联网 发布:hifi音响推荐 知乎 编辑:程序博客网 时间:2024/04/28 05:25

参考网站:http://www.oschina.net/question/987851_145235

一、创建服务端

以PHP为例,首先下载 hprose-php 
下载地址: https://github.com/hprose/hprose-php/archive/master.zip  

解压下载的压缩包,您可以在看到以下文件:

/hprose-php/README_zh_CN.md  是用法说明
/hprose-php/LICENSE.md  则是许可文件,hprose是使用MIT开源许可证,可免费使用。
/hprose-php/php5 文件夹 下面就是hprose的的PHP源码了,将这个目录复制或上传到您的网站任意目录下,

例如复制/hprose-php/php5  到  /example/php5  目录。
然后我们创建一个 /example/index.php 输入下面的PHP代码:

<?php    require_once('php5/HproseHttpServer.php');    function hello($name) {        return 'Hello ' . $name;    }    $server = new HproseHttpServer();    $server->addFunction('hello');    $server->start();?>

常简单,您已经在服务端创建了一个hello函数。

二、AAuto客户端同步调用:

Hprose for AAuto Quicker 的客户端同步调用很简单:

import console;import hprose;//创建客户端var client = hprose.HttpClient("http://hprose.com/example/");//调用服务端函数var str = client.hello("world");//显示函数返回值console.log(str)

服务器端如果发生错误,或者服务器端的服务函数或方法抛出异常,将会被发送到客户端,并且将在客户端抛出异常,你可以使用try语句来捕获它。

三、AAuto客户端异步调用:
在开发 winform 应用时,你最好使用异步调用,这样在通讯中界面也不会发生卡住假死的现象:

import win.ui;/*DSG{{*/var winform = win.form(text="hprose异步调用";right=465;bottom=253)winform.add(button={cls="button";text="调用服务端函数";left=239;top=165;right=379;bottom=203;z=2};edit={cls="edit";left=22;top=15;right=432;bottom=127;edge=1;multiline=1;z=1} )/*}}*/import hprose;winform.button.oncommand = function(id,event){ winform.edit.text = "";    var client = hprose.HttpClient("http://hprose.com/example/");    client.hello("async world", function(result) {        winform.edit.text = '服务端返回值: \r\n' ++ result;    }, function(name, err) {        winform.edit.text = '错误信息: \r\n' ++ err;    }); }winform.show() win.loopMessage();

当用异步调用时,你需要在成功回调函数之后再传递一个错误回调函数来接收服务器端异常(就像上面例子那样)。如果你忽略了该回调函数,客户端将忽略异常,就像从来没发生过一样。

四、hprose javascript版客户端

使用AAuto创建web窗体调用hprose javascript版客户端,
请注意script节点中要使用flashpath指明hproseHttpRequest.swf所在目录。

import win.ui;/*DSG{{*/var winform = ..win.form(text="hprose-javascript测试";right=599;bottom=399) /*}}*/import web.form;var wb = web.form( winform );//创建web窗体wb.html = /**<html><head><script type="text/javascript" src="http://rawgithub.com/hprose/hprose-js/master/dist/hprose.js" flashpath="http://rawgithub.com/hprose/hprose-js/master/dist/"></script></head><body><script type="text/javascript">    var client = new HproseHttpClient("http://www.hprose.com/example/", ["hello"]);    client.hello("World!", function(result) {        alert(result);    }, function(name, err) {        alert(err);    });</script></body> **/ winform.show();  win.loopMessage();


0 0
原创粉丝点击