2016-03-19 39 views
2

我有一个StreamSocket,在我的UWP应用程序关闭期间处理它。我的拥有Socket连接的客户端仍认为连接处于活动状态,即使应用程序已关闭。UWP StreamSocket仅在重新启动应用程序时被强制关闭

只有在重新启动套接字时,我的客户端才会给出'现有连接被强制关闭'异常。

如何关闭套接字以使连接的PC知道连接已关闭?

+0

我有同样的问题,你有没有找到解决方案呢? –

回答

-1

示例的客户端组件创建一个TCP套接字以建立网络连接,使用套接字发送数据并关闭套接字。服务器组件设置一个TCP侦听器,为每个传入的网络连接提供连接的套接字,使用套接字接收来自客户端的数据并关闭套接字。

你可以参考这个GitHub的网址: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/StreamSocket

希望这可以帮助你。

/// <summary> 
    /// This is the click handler for the 'CloseSockets' button. 
    /// </summary> 
    /// <param name="sender">Object for which the event was generated.</param> 
    /// <param name="e">Event's parameters.</param> 
    private void CloseSockets_Click(object sender, RoutedEventArgs e) 
    { 
     object outValue; 
     if (CoreApplication.Properties.TryGetValue("clientDataWriter", out outValue)) 
     { 
      // Remove the data writer from the list of application properties as we are about to close it. 
      CoreApplication.Properties.Remove("clientDataWriter"); 
      DataWriter dataWriter = (DataWriter)outValue; 

      // To reuse the socket with another data writer, the application must detach the stream from the 
      // current writer before disposing it. This is added for completeness, as this sample closes the socket 
      // in the very next block. 
      dataWriter.DetachStream(); 
      dataWriter.Dispose(); 
     } 

     if (CoreApplication.Properties.TryGetValue("clientSocket", out outValue)) 
     { 
      // Remove the socket from the list of application properties as we are about to close it. 
      CoreApplication.Properties.Remove("clientSocket"); 
      StreamSocket socket = (StreamSocket)outValue; 

      // StreamSocket.Close() is exposed through the Dispose() method in C#. 
      // The call below explicitly closes the socket. 
      socket.Dispose(); 
     } 

     if (CoreApplication.Properties.TryGetValue("listener", out outValue)) 
     { 
      // Remove the listener from the list of application properties as we are about to close it. 
      CoreApplication.Properties.Remove("listener"); 
      StreamSocketListener listener = (StreamSocketListener)outValue; 

      // StreamSocketListener.Close() is exposed through the Dispose() method in C#. 
      // The call below explicitly closes the socket. 
      listener.Dispose(); 
     } 

     CoreApplication.Properties.Remove("connected"); 
     CoreApplication.Properties.Remove("adapter"); 
     CoreApplication.Properties.Remove("serverAddress"); 

     rootPage.NotifyUser("Socket and listener closed", NotifyType.StatusMessage); 
    } 
+1

我已经在我的代码中调用了dispose方法,但该行的另一端似乎没有注意到套接字已关闭。只有在重新建立连接似乎导致连接被强制关闭的异常... – WJM

相关问题