原文:UWP使用AppService向另一个UWP客户端应用程序提供服务

在上篇里,我使用的是寄宿在WPF上的WCF进行两个程序间的通信,在解决问题的同时,我的同事也在思考能否使用UWP来做这件事。于是,我们发现了App Service,两个UWP应用沟通的桥梁。

App Service以background task 的形式允许一个UWP向其它UWP提供服务。

首先我们新建一个名为"MyCalculatorService"的Windows Runtime Component项目,新建Calculator类,实现 IBackgroundTask.接口,它很类似WCF里的ServiceContract。

public sealed class Calculator : IBackgroundTask
{
private BackgroundTaskDeferral backgroundTaskDeferral;
private AppServiceConnection appServiceConnection;
public void Run(IBackgroundTaskInstance taskInstance)
{
this.backgroundTaskDeferral = taskInstance.GetDeferral(); var details = taskInstance.TriggerDetails as AppServiceTriggerDetails;
appServiceConnection = details.AppServiceConnection; appServiceConnection.RequestReceived += OnRequestReceived;
taskInstance.Canceled += OnTaskCanceled;
} private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
var messageDeferral = args.GetDeferral();
ValueSet message = args.Request.Message;
ValueSet returnData = new ValueSet(); string command = message["Command"] as string; //Add, Subtract, Multiply, Divide
int? firstNumber = message["Input1"] as int?;
int? secondNumber = message["Input2"] as int?;
int? result = 0; if (firstNumber.HasValue && secondNumber.HasValue)
{
switch (command)
{
case "Add":
{
result = firstNumber + secondNumber;
returnData.Add("Result", result.ToString());
returnData.Add("Status", "Complete");
break;
}
case "Subtract":
{
result = firstNumber - secondNumber;
returnData.Add("Result", result.ToString());
returnData.Add("Status", "Complete");
break;
}
case "Multiply":
{
result = firstNumber * secondNumber;
returnData.Add("Result", result.ToString());
returnData.Add("Status", "Complete");
break;
}
case "Divide":
{
result = firstNumber / secondNumber;
returnData.Add("Result", result.ToString());
returnData.Add("Status", "Complete");
break;
}
default:
{
returnData.Add("Status", "Fail: unknown command");
break;
}
}
} await args.Request.SendResponseAsync(returnData);
messageDeferral.Complete();
} private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
if (this.backgroundTaskDeferral != null)
{
this.backgroundTaskDeferral.Complete();
}
}
}

  然后再新建一个名为MyCalculatorServiceProvider的UWP程序,充当服务端角色,相当于WCF宿主服务的。引用刚才我们创建的wind,然后在 Package.appxmanifest 中声明一个 名为CalculatorService1的App Service 实例,添加 入口点"MyCalculatorService.Calculator"。

现在我们来创建名为“CalculatorClient”的客户端,并调用以上服务。添加以下代码

public sealed partial class MainPage : Page
{
private AppServiceConnection calculatorService; public MainPage()
{
this.InitializeComponent();
} private async void button_Click(object sender, RoutedEventArgs e)
{
//Add the connection
if (calculatorService == null)
{
calculatorService = new AppServiceConnection();
calculatorService.AppServiceName = "CalculatorService1";
calculatorService.PackageFamilyName = "83da5395-2473-49fb-b361-37072e87e9b9_xe3s0d4n4696a"; var status = await calculatorService.OpenAsync(); if (status != AppServiceConnectionStatus.Success)
{
Result.Content = "Failed to connect";
return;
}
} //Call the service
int num1 = int.Parse(InputtextBox1.Text);
int num2 = int.Parse(InputtextBox2.Text);
var message = new ValueSet(); message.Add("Command", Operation.SelectionBoxItem);
message.Add("Input1", num1);
message.Add("Input2", num2); AppServiceResponse response = await calculatorService.SendMessageAsync(message);
string result = ""; if (response.Status == AppServiceResponseStatus.Success)
{
//Get the data that the service sent
if (response.Message["Status"] as string == "Complete")
{
result = response.Message["Result"] as string;
}
}
message.Clear();
ResulttextBlock.Text = result;
}
}

注意其中的AppServiceName是我们在MyCalculatorServiceProvider项目中定义的App Service的Name,PackageFamilyName 是MyCalculatorServiceProvider项目的PackageFamilyName。

完成后,先部署MyCalculatorServiceProvider再部署CalculatorClient,效果是不是跟WCF很类似呢?

好吧,以上都是我从https://social.technet.microsoft.com/wiki/contents/articles/36719.wcf-app-services-in-universal-windows-platform-uwp-using-windows-10.aspx抄的,,,

示例demo可以从这里下http://www.cnblogs.com/luquanmingren/p/7692305.html,没错,我就是懒

UWP使用AppService向另一个UWP客户端应用程序提供服务的更多相关文章

  1. (2/2) 为了理解 UWP 的启动流程,我从零开始创建了一个 UWP 程序

    每次使用 Visual Studio 的模板创建一个 UWP 程序,我们会在项目中发现大量的项目文件.配置.应用启动流程代码和界面代码.然而这些文件在 UWP 程序中到底是如何工作起来的? 我从零开始 ...

  2. (1/2) 为了理解 UWP 的启动流程,我从零开始创建了一个 UWP 程序

    每次使用 Visual Studio 的模板创建一个 UWP 程序,我们会在项目中发现大量的项目文件.配置.应用启动流程代码和界面代码.然而这些文件在 UWP 程序中到底是如何工作起来的? 我从零开始 ...

  3. 我的第一个UWP程序

    1.为什么喜欢UWP 本人无悔入网易云音乐,各种设备上都少不了这个红色图标的软件 从win10发布,网易做了UWP版本的云音乐 应用轻巧.简洁.功能全,接着又下了许多UWP的应用 都给人不一样的感觉, ...

  4. win10 uwp 使用 msbuild 命令行编译 UWP 程序

    原文:win10 uwp 使用 msbuild 命令行编译 UWP 程序 版权声明:博客已迁移到 http://lindexi.gitee.io 欢迎访问.如果当前博客图片看不到,请到 http:// ...

  5. 理解 UWP 视图的概念,让 UWP 应用显示多个窗口(多视图)

    原文 理解 UWP 视图的概念,让 UWP 应用显示多个窗口(多视图) UWP 应用多是一个窗口完成所有业务的,事实上我也推荐使用这种单一窗口的方式.不过,总有一些特别的情况下我们需要用到不止一个窗口 ...

  6. 我的第一个REST客户端程序!

    Delphi:XE8 看了好几天的资料了,也没有弄出来一个REST程序,尝试了XE8中带的例子,也都没有搞懂.我在网上不断搜索,看是否能够找到适合自己的文章,希望能够做出来一个REST的小例子,万幸, ...

  7. zabbix学习-如何部署一个agent客户端

    1. 部署一个agent客户端很简单,比如监控服务器本身 yum install zabbix-agent -y 2.配置文件位置: vim /etc/zabbix/zabbix-agendt.con ...

  8. 使用c++实现一个FTP客户端(一)

    之前使用c++实现了一个FTP客户端,在这里做一些记录. 一.需要注意的几点 ①FTP是一种文件传输协议,基于TCP,所以客户端与服务器建立的连接是可靠.安全的,并且要经过三次握手的过程. ②FTP传 ...

  9. 学习T-io框架,从写一个Redis客户端开始

    前言   了解T-io框架有些日子了,并且还将它应用于实战,例如 tio-websocket-server,tio-http-server等.但是由于上述两个server已经封装好,直接应用就可以.所 ...

随机推荐

  1. poj2151之概率DP

    Check the difficulty of problems Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 4403   ...

  2. 【a703】求逆序对(线段树的解法)

    Time Limit: 10 second Memory Limit: 2 MB 问题描述 给定一个序列a1,a2...an.如果存在i小于j 并且ai大于aj,那么我们称之为逆序对,求给定序列中逆序 ...

  3. js的dom对象(带实例超详细全解)

    js的dom对象(带实例超详细全解) 一.总结 一句话总结: 1.DOM中的方法区分大小写么? 解答:区分 2.DOM中元素和节点的关系式什么? 解答:元素就是标签,节点中有元素节点,也是标签,节点中 ...

  4. Java: Map里面的键和值可以为空吗?

    在Java中,Map里面的键和值可以为空吗?我们先来看一个例子: private static void TestHashMap() { // TODO Auto-generated method s ...

  5. 双机热备的Quartz集群

    sqlserver搭建高可用双机热备的Quartz集群部署[附源码]   一般拿Timer和Quartz相比较的,简直就是对Quartz的侮辱,两者的功能根本就不在一个层级上,如本篇介绍的Quartz ...

  6. SQL表的默认常用数据类型

    分类 字段类型 描述 整数 bit 0或1的整型数字 int 从-2^31(-2,147,483,648)到2^31-1(2,147,483,647)的整型数字 smallint 从-2^15(-32 ...

  7. 策略模式的JS实现

    var S = function (salary) { return salary * 4; }; var A = function (salary) { return salary * 3; }; ...

  8. WPF中 PropertyPath XAML 语法

    原文:WPF中 PropertyPath XAML 语法 PropertyPath 对象支持复杂的内联XAML语法用来设置各种各样的属性,这些属性把PropertyPath类型作为它们的值.这篇文章讨 ...

  9. Attribute-based identification schemes for objects in internet of things

    Methods and arrangements for object identification. An identification request is received from diffe ...

  10. 【Python注意事项】如何理解python中间generator functions和yield表情

    本篇记录自己的笔记Python的generator functions和yield理解表达式. 1. Generator Functions Python支持的generator functions语 ...