使用 windows 10 个通用应用程序进行客户端服务器编程

client server programming with windows 10 universal apps

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

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

您可以使用 WCF, there is no special consideration in implementing the server to support a Universal App client, client needs to support the protocol which universal apps do. There is a pretty old sample here,但它也应该适用于当今的通用应用程序。

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

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

如果您需要将数据发送回客户端,您可以将每个客户端套接字添加到一个以 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;
      }
 }