简体   繁体   English

如何处理与 Windows StreamSocket 的断开/重新连接

[英]How to handle disconnection / reconnection with windows StreamSocket

What is the correct way to handle a disconnection and re-connection event with the windows StreamSocket class (TCP)?使用 Windows StreamSocket 类 (TCP) 处理断开连接和重新连接事件的正确方法是什么?

I have an issue where calling "Invalid Operation, method was called at an unexpected time" when calling async_connect after a disconnection event我有一个问题,即在断开连接事件后调用 async_connect 时调用“无效操作,方法在意外时间被调用”

do I need to create a new streamsocket, or wait for some amount of time before attempting to re-connect?我是否需要创建一个新的流套接字,或者在尝试重新连接之前等待一段时间?

https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.streamsocket https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.streamsocket

The solution was to add the following code:解决方案是添加以下代码:

// on catching an exception
socket.dispose();
connect();

// connect function
connect():
    socket = new StreamSocket ...

It was necessary to 1) call socket.dispose() on the socket which the client disconnected from and 2) create a new socket (socket = new StreamSocket(...)).有必要 1) 在客户端断开连接的套接字上调用 socket.dispose() 和 2) 创建一个新的套接字 (socket = new StreamSocket(...))。 Reusing the same socket to connect did not work.重用相同的套接字进行连接不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM