使用异步方式调用WebService

       在很多情况下我们可能都要使用异步调用WEBService。使用异步的好处是非阻塞方式进行的。当然也增加一定的编程难度。使用异步编程,我们可以实现对远程服务的调用,查询调用状态,或取消调用等功能。

我们以代码实例为例来解说
首先使用VS2k3建立一个WEBSERVICE ,假设是一个提供股票信息的服务。这里我处理的比较简单,仅是模拟一下服务调用需要很长的时间。
namespace StockService
{
 /// <summary>
 /// Service1 的摘要说明。
 /// </summary>
 public class StockPrice : System.Web.Services.WebService
 {
  public StockPrice()
  {
   //CODEGEN: 该调用是 ASP.NET Web 服务设计器

所必需的
   InitializeComponent();
  }

  #region 组件设计器生成的代码
  
  //Web 服务设计器所必需的
  private IContainer components = null;
    
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if(disposing && components != null)
   {
    components.Dispose();
   }
   base.Dispose(disposing);  
  }
  
  #endregion

  [WebMethod]
  public double getStockPrice(String stockSymbol)
  {
   //在这里我们进行模拟处理,线程暂停5秒
   Thread.Sleep(5000);
   return new Random().NextDouble() + 15.0;
  }
  [WebMethod]
  public double getStockPrice1(String stockSymbol)
  {
   //在这里我们进行模拟处理,线程暂停5秒
   Thread.Sleep(5000);
   return new Random().NextDouble() + 15.0;
  }
  [WebMethod]
  public double getStockPrice2(String stockSymbol)
  {
   //在这里我们进行模拟处理,线程暂停5秒
   Thread.Sleep(5000);
   return new Random().NextDouble() + 15.0;
  }

 }
}


然后我们建立一个WINFORM程序来充当客户端调用刚才建立的WEBSERVICE。这里我们有很多种方式来实现异步调用(包括自己建立一个线程来调用服务,当服务完成后,使用delegate来实现事件的回调)。这种方法我们先排除掉。因为当你添加一个WEB引用到本地工程时,代理类里已实现了异步调用的代码。
 public class Form2 : System.Windows.Forms.Form
 {
  private localhost.StockPrice m_stockService;
  private IAsyncResult m_handle;
  private System.Windows.Forms.Button button1;
  private System.Windows.Forms.Button button2;
  private System.Windows.Forms.Button button3;
  private System.Windows.Forms.Button button4;
  private System.Windows.Forms.TextBox messageBox;
  private System.Windows.Forms.Button button5;
  private System.Windows.Forms.Button button6; 

  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private System.ComponentModel.Container components = null;

  public Form2()
  {
   //
   // Windows 窗体设计器支持所必需的
   //
   InitializeComponent();

   //
   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
   //
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if(components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows 窗体设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.messageBox = new System.Windows.Forms.TextBox();
   this.button1 = new System.Windows.Forms.Button();
   this.button2 = new System.Windows.Forms.Button();
   this.button3 = new System.Windows.Forms.Button();
   this.button4 = new System.Windows.Forms.Button();
   this.button5 = new System.Windows.Forms.Button();
   this.button6 = new System.Windows.Forms.Button();
   this.SuspendLayout();
   //
   // messageBox
   //
   this.messageBox.Location = new System.Drawing.Point(16,8);
   this.messageBox.Multiline = true;
   this.messageBox.Name = "messageBox";
   this.messageBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
   this.messageBox.Size = new System.Drawing.Size(656,320);
   this.messageBox.TabIndex = 0;
   this.messageBox.Text = "";
   //
   // button1
   //
   this.button1.Location = new System.Drawing.Point(24,344);
   this.button1.Name = "button1";
   this.button1.TabIndex = 1;
   this.button1.Text = "调用";
   this.button1.Click += new System.EventHandler(this.button1_Click);
   //
   // button2
   //
   this.button2.Location = new System.Drawing.Point(128,344);
   this.button2.Name = "button2";
   this.button2.TabIndex = 2;
   this.button2.Text = "轮询";
   this.button2.Click += new System.EventHandler(this.button2_Click);
   //
   // button3
   //
   this.button3.Location = new System.Drawing.Point(240,344);
   this.button3.Name = "button3";
   this.button3.TabIndex = 3;
   this.button3.Text = "中止";
   this.button3.Click += new System.EventHandler(this.button3_Click);
   //
   // button4
   //
   this.button4.Location = new System.Drawing.Point(352,344);
   this.button4.Name = "button4";
   this.button4.Size = new System.Drawing.Size(96,23);
   this.button4.TabIndex = 4;
   this.button4.Text = "等待异步操作";
   this.button4.Click += new System.EventHandler(this.button4_Click);
   //
   // button5
   //
   this.button5.Location = new System.Drawing.Point(464,344);
   this.button5.Name = "button5";
   this.button5.Size = new System.Drawing.Size(120,23);
   this.button5.TabIndex = 5;
   this.button5.Text = "一次调用三个服务";
   this.button5.Click += new System.EventHandler(this.button5_Click);
   //
   // button6
   //
   this.button6.Location = new System.Drawing.Point(608,344);
   this.button6.Name = "button6";
   this.button6.TabIndex = 6;
   this.button6.Text = "回调处理";
   this.button6.Click += new System.EventHandler(this.button6_Click);
   //
   // Form2
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6,14);
   this.ClientSize = new System.Drawing.Size(696,477);
   this.Controls.Add(this.button6);
   this.Controls.Add(this.button5);
   this.Controls.Add(this.button4);
   this.Controls.Add(this.button3);
   this.Controls.Add(this.button2);
   this.Controls.Add(this.button1);
   this.Controls.Add(this.messageBox);
   this.Name = "Form2";
   this.Text = "Form2";
   this.Load += new System.EventHandler(this.Form2_Load);
   this.ResumeLayout(false);

  }
  #endregion

  private void Form2_Load(object sender,System.EventArgs e)
  {
  
  }

  //你调用BegingetStockPrice()后得到一个具有IAsyncResult界面的对象。
  //它提供了IsCompleted的属性。当这个值为"True"的时候,
  //你就可以通过调用EndgetStockPrice()来拿到函数运行的结果。
  //更重要的是,你可以在异步调用的时候"放弃Abort"调用。
  //下面的程序段是用3个"按钮(Button)"来示意如何使用异步调用,检查调用是否结束以及放弃调用。

  //异步调用WebMethod
  private void button1_Click(object sender,System.EventArgs e)
  {
   m_stockService = new localhost.StockPrice();
   m_handle = m_stockService.BegingetStockPrice("IBM",null,null);
   messageBox.Text += "正在调用WEB服务." + System.Environment.NewLine;

  }
  //检查异步调用是否完成。如果完成的话,就取出调用结果
  private void button2_Click(object sender,System.EventArgs e)
  {
   if(m_handle==null)
   {
    messageBox.Text += "没有服务被调用!"+System.Environment.NewLine;
    return;
   }
   if(m_handle.IsCompleted == false)
    messageBox.Text += "服务正在调用中"  + System.Environment.NewLine;
   else
   {
    double price = m_stockService.EndgetStockPrice(m_handle);
    messageBox.Text += "金额为: " + price + System.Environment.NewLine;
   }

  }

  //放弃异步调用
  private void button3_Click(object sender,System.EventArgs e)
  {
   if(m_handle!=null)
   {
    WebClientAsyncResult result = (WebClientAsyncResult)m_handle;
    result.Abort();
    m_handle = null;
   }
   messageBox.Text += "调用服务被用户终止" + System.Environment.NewLine;

  }

  //使用WaitHandle
  //你调用BegingetStockPrice()后得到一个具有IAsyncResult界面的对象。
  //它提供了AsyncWaitHandle的属性。调用它的WaitOne()函数可以使程序被阻拦直到另外一个线程函数调用完成。
  //之后程序将继续往下执行。
  private void button4_Click(object sender,System.EventArgs e)
  {
   if(this.m_stockService ==null)
    m_stockService = new localhost.StockPrice();
   m_handle = m_stockService.BegingetStockPrice("IBM",null);
   messageBox.Text  += "正在调用服务" + System.Environment.NewLine;
   m_handle.AsyncWaitHandle.WaitOne();
   double price = m_stockService.EndgetStockPrice(m_handle);
   messageBox.Text += "金额为: " + price + System.Environment.NewLine;  

  }

  //从现象上看,和同步调用相比你并没有得到好处。程序等待的时候仍然处于"挂起"状态。
  //但是在有些情况下,"等待"还是有它的特色的。
  //比如说你可以连续调用三个WebMethod,如果每个函数费时5秒,
  //那么使用同步的话总共会使用15秒钟。但如果使用异步的话,你可能只要等待5秒钟。
  //当然这要使用WaitHandle提供的WaitAll()函数。如下所示:
  //一次调用三个服务
  private void button5_Click(object sender,System.EventArgs e)
  {
   
   if(this.m_stockService ==null)
    m_stockService = new localhost.StockPrice();
   IAsyncResult[] handles = new IAsyncResult[3];
  
   messageBox.Text  += "一次调用三个服务:开始时间为"+DateTime.Now.ToString() + System.Environment.NewLine;
   handles[0] = m_stockService.BegingetStockPrice("IBM",null);
   handles[1] = m_stockService.BegingetStockPrice1("MS",null);
   handles[2] = m_stockService.BegingetStockPrice2("SUN",null);
   
   WaitHandle[] WaitHandles ={
    handles[0].AsyncWaitHandle,
    handles[1].AsyncWaitHandle,
    handles[2].AsyncWaitHandle};
  
   //函数被阻拦,直到3个函数都执行完毕。WaitAny()函数情况类似,但有一个函数完成后
   //程序就解阻,继续往下执行
   WaitHandle.WaitAll(WaitHandles);
   messageBox.Text+="调用完成时间为:"+DateTime.Now.ToString()+ System.Environment.NewLine;
   double[] prices = new double[3];
   for(int i=0;i<3;i++)
   {
    prices[i] = m_stockService.EndgetStockPrice(handles[i]);  
    messageBox.Text += "金额为: " + prices[i] +
     System.Environment.NewLine;
   }
   messageBox.Text  += "调用三个服务完毕:" + System.Environment.NewLine;
  }

  //看到现在,你可能还没有感到满意。因为你异步调用了函数后,还要手工检查函数是否执行完毕,
  //或者要处于等待状态。能否让函数完成后,自动显示结果或是做其它操作呢?
  //答案是"能"的。回调函数就是做这种事情的。
  private void button6_Click(object sender,System.EventArgs e)
  {
   if(this.m_stockService ==null)
    m_stockService = new localhost.StockPrice();
   //生成回调函数
   AsyncCallback cb = new AsyncCallback (this.callback);
   m_stockService.BegingetStockPrice("IBM",cb,DateTime.Now);
   messageBox.Text  += "远程服务被调用" + System.Environment.NewLine;

  }  private void callback(IAsyncResult handle)  {   double price = m_stockService.EndgetStockPrice(handle);   lock(this)   {    messageBox.Text += "金额为: " + price + ". 请求时间: " +     handle.AsyncState.ToString() + ",结束时间: " +     DateTime.Now.ToString() +     System.Environment.NewLine;   }  } }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


1.使用ajax调用varxhr;functioninvoke(){if(window.ActiveXObject){xhr=newActiveXObject("Microsoft.XMLHTTP");}else{xhr=newXMLHttpRequest();}//指定请求地址varurl="http://127.0.0.1:7777/hello?wsdl";//
               好不容易把WebService服务器端搭建起来,我们还需要客户端程序也同样跑起来才能够进行和服务器端程序的通信: 在这篇文章里面,我会先自己写代码去实现调用WebService服务器端程序,接下来,通过IDEA配置的方式来调用WebService服务端: 首先,我写了一个W
1新建一个工程项目用来做服务端增加一个MyService1类文件packagecom.zns.ws;importjavax.jws.WebMethod;importjavax.jws.WebService;importjavax.xml.ws.Endpoint;@WebServicepublicclassMyService1{publicstaticvoidmain(String[]args){
packagecom.transsion.util;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.URL;importjava.net.URLConnection;importcom.alibaba.druid.util.Base64;importcom.tra
再生产wsdl文件时重写描述文件1usingSystem;2usingSystem.Collections.Generic;3usingSystem.Linq;4usingSystem.Web;5usingSystem.Web.Services.Description;67namespaceStrongSoftManage.Web.App8{9publicclassSoapExtens:SoapExtensi
一般情况下,使用eclipse自带的jax-ws生成webservice会自动生成2个类:ContractConnector.java packagecom.wonders.webservice.contract;importjava.text.DecimalFormat;importjava.text.ParseException;importjava.text.SimpleDateFormat;importjava.util.Date;i
一、WebService概述1.1什么是WebService 基于Web的服务:服务器端整出一些资源让客户端应用访问(获取数据) 一个跨语言、跨平台的规范(抽象)所谓跨编程语言和跨操作平台,就是说服务端程序采用java编写,客户端程序则可以采用其他编程语言编写,反之亦然!跨操作系统平台则是指服务
一、什么是CXF?    ApacheCXF=Celtix+Xfire,开始叫ApacheCeltiXfire,后来更名为ApacheCXF了,以下简称为CXF。ApacheCXF是一个开源的webServices框架,CXF帮助您构建和开发webServices,它支持多种协议,比如:SOAP1.1,1,2 XML/HTTP、RESTful或者CORBA。  
工具IDEA一、构建项目1、选择SpringInitializr2、填写项目信息3、勾选webService4、勾选Thymeleaf5、项目建立完成,启动类自动生成二、写个Controller启动服务。浏览器访问/hello接口。 
1.环境win764位,vs20102.新建一个asp.netweb应用程序(同上一篇)3.添加一个web引用,引用上一篇创建的服务。注意不是服务引用。如下图 
WebService之WSDL文件讲解   恩,我想说的是,是不是经常有人在开发的时候,特别是和第三方有接口的时候,走的是SOAP协议,然后用户给你一个WSDL文件,说按照上面的进行适配,嘿嘿,这个时候,要是你以前没有开发过,肯定会傻眼,那如果你想学习的话,就认真的看下面的讲解咯:一、WSDL概述  
在websrvice发布文件的webconfig中加入<httpRuntimemaxRequestLength="102400"/> <webServices>     <protocols>       <addname="HttpPost"/>       <addname="HttpGet"/>     </protocols>   
 代码比较简单,按照如下来操作即可,只是jar包有很多问题,比如找不到classnotFondspring、以及找不到xfile.xml、以及xfile.xml中的一个参数问题,以及2.0 spring。jar和spring1.6.2冲突问题,总之这个小demo报了一堆错误,其实都是jar的问题,为了让大家减少这方面的错误,所以我提供
 一、soapUI简介SOAP:   WebService通过Http协议发送请求和接收结果时,发送的请求内容和结果内容都采用XML格式封装,并增加了一些特定的HTTP消息头,以说明HTTP消息头的内容格式,这些特定的HTTP消息头和XML内容格式就是SOAP协议。SOAP提供了标准的RPC方法来调用WebService。 
参考,感谢https://blog.csdn.net/hj7jay/article/details/727224381.环境:win764位,jdk1.8.0_201 EclipseJavaEEIDEforWebDevelopers.Version:Mars.1Release(4.5.1)2.创建一个普通的java项目,名字是TheService在src目录下创建一个com.hyan.service包,在此包下创建
CXF实现RestfulWebService基础示例一、写在前面IDE:IDEA14JDK:1.7CXF:2.6.2示例来源:%CXF_HOME%\samples\jax_rs\basic发布方式:JAXRSServerFactoryBean的create()方法调用方式:URL的openStream()方法、HttpClient的executeMethod()方法二、服务端(Java项目)1.准备Jar包
封装helper类:classWebServiceHelper{///<summary>///1.get请求http方法///</summary>///<paramname="url">基础url</param>///<paramname="method">请求方法</param>///<paramnam
.net客户端调用java或.netwebservice进行soapheader验证最近项目中有业务需要跨平台调用web服务,客户端和服务器之间采用非对称加密来保证数据的安全性,webservice的安全验证基于soapheader。借此机会,顺便整理一下调用.netwebservice和javawebservice的验证方式,记录下来。
Node.jshttps://www.cnblogs.com/goldlong/p/8027997.htmlQQ音乐apihttps://juejin.im/post/5a35228e51882506a463b172#heading-11?tdsourcetag=s_pcqq_aiomsgGit把本地仓库上传到GitHbubhttps://blog.csdn.net/zamamiro/article/details/70172900git删除本地仓库https://blog.cs
转载自:孤傲苍狼 WebService学习总结(三)——使用JDK开发WebService一、WebService的开发手段使用Java开发WebService时可以使用以下两种开发手段1、 使用JDK开发(1.6及以上版本)-->详见:本文2、使用CXF框架开发-->详见:其他文章二、使用JDK开发WebServi