网络开发之使用Web Service和使用WCF服务

  判断是否有可用网络连接可以通过NetworkInterface类中的GetIsNetworkAvailable来实现:
    bool networkIsAvailable = networkInterface.

使用Web服务

  Web服务(Web Service)就是通过标准的XML数据格式和通用扽互联网协议为其他应用程序提供联系或信息的。为其他应用程序提供服务时,Web Service可以以接口的方式接受合法的请求并返回相应的服务和功能。

使用Web Service

  使用Web Service前需生成一个Web Service代理,在命名空间中加入该Web Service代理的命名空间。 实例化服务引用 返回数据事件 异步调用方法

  下面实例是使用Web Service,查询城市天气预报
    应用调用的查询城市天气预报的web service接口为:
      http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

    首先添加webservice的引用,将web service服务加入,这时生成了上述web服务在本地的一个代理。
    打开“解决方案资源管理器”,右击“引用”节点,从弹出的菜单中选择“添加服务引用”。
    在弹出的对话框中,“地址”处输入上文中提到的Web服务的地址,并点击“前往”按钮,待发现WEB服务完成后。在“命名空间”处输入一个有效命名空间名字。接着点击“确定”。
    切换到后台代码,调用web service服务,完成查询按钮的单击事件处理。
    主要代码如下:

      MainPage.xaml

1 <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
2             <TextBlock HorizontalAlignment="Left" Height="66" Margin="9,17,0,0" TextWrapping="Wrap" Text="请输入要查询的城市" FontSize="30"  VerticalAlignment="Top" Width="437"/>
3             <TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="90" Margin="0,83,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="446"/>
4             <!--<TextBlock x:Name="textBlock1" HorizontalAlignment="Left" Height="319" Margin="10,178,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="436"/>-->
5             <ListBox Name="myListBox" HorizontalAlignment="Left" Height="319" Margin="10,178,0,0" VerticalAlignment="Top" Width="436" ItemsSource="{Binding }"/>
6             <Button Content="查    询" FontSize="35" HorizontalAlignment="Left" Height="95" Margin="40,502,0,0" VerticalAlignment="Top" Width="334" Click="Button_Click_1"/>
7 </Grid>
View Code

      Mainpage.xaml.cs

 1         private void Button_Click_1(object sender, RoutedEventArgs e)
 2         {
 3             ServiceReference1.WeatherWSSoapClient ww = new ServiceReference1.WeatherWSSoapClient();
 4             ww.getWeatherCompleted += new EventHandler<ServiceReference1.getWeatherCompletedEventArgs>(ww_getWeatherCompleted);
 5             ww.getWeatherAsync(textBox1.Text,"");
 6         }
 7   void ww_getWeatherCompleted(object sender, ServiceReference1.getWeatherCompletedEventArgs e)
 8         {
 9             string[] result = e.Result;
10             string res = "";
11             if (result.Length > 0)
12             {
13                 foreach (string s in result)
14                 {
15                     myListBox.Items.Add(s);
16                     myListBox.Items.Add(res);
17                 }
18             }
19 
20         }
View Code

使用WCF服务

  WCF(Windows Communication Foundation),是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯基础。 它是.NET框架的一部分。由 .NET Framework 3.0 开始引入。

  WCF的最终目标是通过进程或不同的系统、通过本地网络或是通过Internet收发客户和服务之间的消息。

  WCF合并了Web服务、.net Remoting、消息队列和Enterprise Services的功能并集成在Visual Studio中。

  WCF专门用于面向服务开发。 使用WCF使用方法和使用Web Service相似。

  使用WCF前需生成一个代理,在命名空间中加入该代理的命名空间。 实例化服务引用 返回数据事件 异步调用方法

原文地址:https://www.cnblogs.com/spilledlight/p/4886007.html