使用windows10通用应用程序进行客户端-服务器编程

本文关键字:客户端 服务器 编程 windows10 应用程序 使用 | 更新日期: 2023-09-27 18:19:55

我想创建一个客户端/服务器系统,其中客户端是一个收集数据的(C#)Windows 10通用应用程序,服务器是一个C#程序(某种形式),可以对客户端进行身份验证、发送和接收收集的数据等。

我已经编写了客户端通用应用程序的基本内容,现在需要完成网络部分。有人能提出一个框架+如何构建连接到windows 10通用应用程序的服务器的例子吗?我正在研究windows通信框架,但我还没有找到任何将它们集成到通用应用程序中的例子。

使用windows10通用应用程序进行客户端-服务器编程

你可以使用WCF,在实现服务器以支持通用应用程序客户端时没有特别的考虑,客户端需要支持通用应用所做的协议。这里有一个很旧的示例,但它也应该适用于今天的通用应用程序。

需要记住的一件事是,如果要将应用程序发布到应用商店,则应用程序和服务器不能在同一台计算机上运行,因为Windows应用商店应用程序不允许连接到localhost。

下面是我在应用程序中使用的StreamSocketListener类的服务器端实现的一个基本示例。我在这个例子中使用了一个静态类。您还需要客户端的逻辑。

如果需要将数据发送回客户端,可以将每个客户端套接字添加到以IP(或其他标识符)为密钥的字典集合中。

希望能有所帮助!

// Define static class here.
public static StreamSocketListener Listener { get; set; }
// This is the static method used to start listening for connections.
 public static async Task<bool> StartServer()
 {
      Listener = new StreamSocketListener();
      // Removes binding first in case it was already bound previously.
      Listener.ConnectionReceived -= Listener_ConnectionReceived;
      Listener.ConnectionReceived += Listener_ConnectionReceived;
      try
      {
           await Listener.BindServiceNameAsync(ViewModel.Current.Port); // Your port goes here.
           return true;
       }
       catch (Exception ex)
       {
          Listener.ConnectionReceived -= Listener_ConnectionReceived;
          Listener.Dispose();
          return false;
        }
 }
 private static async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
      var remoteAddress = args.Socket.Information.RemoteAddress.ToString();
      var reader = new DataReader(args.Socket.InputStream);
      var writer = new DataWriter(args.Socket.OutputStream);
      try
      {
          // Authenticate client here, then handle communication if successful.  You'll likely use an infinite loop of reading from the input stream until the socket is disconnected.
      }
      catch (Exception ex)
      {
           writer.DetachStream();
           reader.DetachStream();
           return;
      }
 }