我有一个 StreamSocket,我在关闭 UWP 应用程序期间将其丢弃。我的具有 Socket 连接的客户端仍然认为连接是事件的,即使应用程序已经关闭。
只有在重新启动套接字时,我的客户端才会给出“现有连接被强制关闭”的异常。
如何以连接的 PC 知道连接已关闭的方式关闭 Socket?
最佳答案
示例的客户端组件创建一个 TCP 套接字来建立网络连接,使用套接字发送数据,然后关闭套接字。服务器组件设置一个 TCP 监听器,为每个传入的网络连接提供一个已连接的套接字,使用套接字从客户端接收数据,然后关闭套接字。
您可以引用这个 GitHub URL: 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);
}
关于c# - UWP StreamSocket 仅在重启应用时被强行关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36104844/