How to reuse socket in .NET?
- by Hermann
I am trying to reconnect to a socket that I have disconnected from but it won't allow it for some reason even though I called the Disconnect method with the argument "reuseSocket" set to true.
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(ipAddress, port);
//...receive data
_socket.Disconnect(true); //reuseSocket = true
//...wait
_socket.Connect(ipAddress, port); //throws an InvalidOperationException:
Once the socket has been disconnected,
you can only reconnect again
asynchronously, and only to a
different EndPoint. BeginConnect must
be called on a thread that won't exit
until the operation has been
completed.
What am I doing wrong?