Search code examples
c#tcpstream-socket-clientwindows-networking

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)?

I have an issue where calling "Invalid Operation, method was called at an unexpected time" when calling async_connect after a disconnection event

do I need to create a new streamsocket, or wait for some amount of time before attempting to re-connect?

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


Solution

  • 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(...)). Reusing the same socket to connect did not work.