UWP应用程序不从localhost上的.NET桌面应用程序接收UDP数据报

我一直在尝试在作为客户端的UWP应用程序和作为服务器的.NET桌面应用程序之间设置客户端服务器。 我正在使用UDP Datagrams作为两者之间的消息传递系统。

这是我的UWP代码,用于在端口22222上侦听localhost IP上的Datagrams:

private async void listenToServer() { // Setup UDP Listener socketListener = new DatagramSocket(); socketListener.MessageReceived += MessageReceived; await socketListener.BindEndpointAsync(new HostName("127.0.0.1"),"22222"); Debug.WriteLine("Listening: " + socketListener.Information.LocalAddress + " " + socketListener.Information.LocalPort); } private async void MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { // Interpret the incoming datagram's entire contents as a string. uint stringLength = args.GetDataReader().UnconsumedBufferLength; string receivedMessage = args.GetDataReader().ReadString(stringLength); Debug.WriteLine("Received " + receivedMessage); } 

这是我的WinForm .NET桌面应用程序,用于在端口2222上的localhost上发送Datagrams:

 public async void sendToClient() { // Setup UDP Talker talker = new UdpClient(); sending_end_point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 22222); talker.Connect(sending_end_point); byte[] send_buffer = Encoding.ASCII.GetBytes("Hello!"); await talker.SendAsync(send_buffer, send_buffer.Length); } 

这是我尝试过的,以及我从故障排除中得到的知识:

  1. UWP向.NET桌面发送UDP数据报。

    通过localhost端口11111向.NET桌面发送消息的UWP代码:

     public async void sendToServer() { // Connect to the server socketTalker = new DatagramSocket(); await socketTalker.ConnectAsync(new HostName("127.0.0.1"), "11111"); Debug.WriteLine("Connected: " + socketTalker.Information.RemoteAddress + " " + socketTalker.Information.RemotePort); // Setup Writer writer = new DataWriter(socketTalker.OutputStream); writer.WriteString("Ping!"); await writer.StoreAsync(); writer.DetachStream(); writer.Dispose(); } 

    .NET桌面代码,用于通过相同的IP和端口侦听来自UWP的消息:

     private async Task listenToClient() { // Setup listener listener = new UdpClient(11111); UdpReceiveResult receiveResult = await listener.ReceiveAsync(); Debug.WriteLine(" Received: " + Encoding.ASCII.GetString(receiveResult.Buffer)); } 
  2. 从.NET桌面向UWP发送UDP数据报在不同的IP(2台不同的计算机)上运行

    我已经通过将侦听器和讲话者IP地址设置为运行服务器的同一IP地址来测试它,并且它可以完美地工作。 这导致研究让我进入#3 ……

  3. 环回豁免没有任何区别

    运行CheckNetIsolation.exe和Loopback免除工具以免除UWP应用程序的环回IP限制并未解决此问题。 看起来应该没关系,从我读到的内容( Windows 10.UWP中的UDP问题 ),在Visual Studio环境中运行应该已经免于环回,但我还是尝试过,而不是运气。

尽管这很糟糕,但它被微软设计阻止了。

环回仅允许用于开发目的。 不允许在Visual Studio外部安装Windows运行时应用程序。 此外,Windows运行时应用程序只能将IP环回用作客户端网络请求的目标地址。 因此,使用DatagramSocket或StreamSocketListener监听IP环回地址的Windows运行时应用程序无法接收任何传入数据包。

资料来源: https : //msdn.microsoft.com/en-us/library/windows/apps/hh780593.aspx

您可以做的最佳解决方法是使用TCP套接字并从UWP应用程序连接到您的桌面应用程序(而不是相反)。