我有一个StreamSocket,我在关闭UWP应用程序时将其丢弃。我的具有Socket连接的客户端仍然认为连接是活动的,即使应用程序已关闭。
只有在重新启动Socket时,我的客户才会给出“现有连接被强行关闭”的异常。
如何以连接的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);
}