UWP(Universal Windows Platform)应用程序:UWP是微软推出的一个应用程序平台,旨在支持跨多个设备(如桌面、平板、手机等)的应用开发。UWP应用程序使用XAML进行UI设计,并使用C#、C++或VB.NET等语言进行编程。
Windows服务:Windows服务是一种在后台运行的程序,不需要用户交互即可执行特定任务。它们通常用于系统级操作,如日志记录、数据同步等。
UWP应用程序与Windows服务之间的通信可以通过以下几种方式实现:
Windows服务端代码(C#):
using System;
using System.IO.Pipes;
class PipeServer
{
static void Main()
{
using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe"))
{
Console.WriteLine("NamedPipeServerStream object created.");
// Wait for a client to connect
pipeServer.WaitForConnection();
Console.WriteLine("Client connected.");
using (StreamReader sr = new StreamReader(pipeServer))
{
string temp;
while ((temp = sr.ReadLine()) != null)
{
Console.WriteLine("Received from client: {0}", temp);
}
}
}
}
}
UWP客户端代码(C#):
using System;
using System.IO.Pipes;
class PipeClient
{
static void Main()
{
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe", PipeDirection.Out))
{
Console.WriteLine("NamedPipeClientStream object created.");
// Connect to the server
pipeClient.Connect();
Console.WriteLine("Client connected.");
using (StreamWriter sw = new StreamWriter(pipeClient))
{
sw.WriteLine("Hello, Server!");
sw.Flush();
}
}
}
}
Windows服务端代码(C#):
using System;
using System.ServiceModel;
[ServiceContract]
public interface IMyService
{
[OperationContract]
string GetMessage(string name);
}
public class MyService : IMyService
{
public string GetMessage(string name)
{
return string.Format("Hello, {0}!", name);
}
}
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(MyService), new Uri("net.pipe://localhost")))
{
host.AddServiceEndpoint(typeof(IMyService), new NetNamedPipeBinding(), "MyService");
host.Open();
Console.WriteLine("Service is ready.");
Console.ReadLine();
}
}
}
UWP客户端代码(C#):
using System;
using System.ServiceModel;
using System.Threading.Tasks;
[ServiceContract]
public interface IMyService
{
[OperationContract]
string GetMessage(string name);
}
public class MyServiceClient : ClientBase<IMyService>, IMyService
{
public MyServiceClient(Binding binding, EndpointAddress endpointAddress)
: base(binding, endpointAddress)
{
}
public string GetMessage(string name)
{
return Channel.GetMessage(name);
}
}
class Program
{
static async Task Main(string[] args)
{
using (MyServiceClient client = new MyServiceClient(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyService")))
{
string result = await client.GetMessageAsync("World");
Console.WriteLine(result);
}
}
}
[ServiceContract]
和[OperationContract]
。System.ServiceModel.ServiceHost
。通过以上方法,您可以实现UWP应用程序与Windows服务之间的通信,并解决常见的通信问题。
领取专属 10元无门槛券
手把手带您无忧上云