Reputation: 1721
I have a windows service written around some code similar to this Asynchronous Server Socket Example
Everything works great. Client/Server communication works perfectly. No issues at all. When I try to shutdown the windows service, I can't stop the server socket listener without getting the following error:
A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.
I have tried every combination of the following to stop listening. But they all throw the error.
listener.Shutdown(SocketShutdown.Both);
listener.Disconnect(true);
listener.Close();
Even though it errors, the socket does eventually release and shuts down. However, it can take up to a minute before I can restart my windows service. I need to be able to cycle the windows service faster than that. Please let me know if you can help. Thanks...
Upvotes: 4
Views: 2820
Reputation: 1771
Try setting the LingerState property
socket.LingerState = new LingerOption(false, 0);
socket.Shutdown(SocketShutdown.Both);
socket.Disconnect(false);
socket.Close();
Hope this helps.
Upvotes: 1
Reputation: 96159
listener is the socket you're using for .Bind(), .Listen() and .Accept(), i.e. it's not the socket that connects via .Connect() or is the accepted connection via .Accept()?
Then don't call listener.Discconnect().
"Useless" details:
System.Net.Socket.Disconnect uses an (unsafe) function pointer to call the (native) winsock extension function DisconnectEx:
ParametersYour listener socket is not in a connected state.
hSocket [in]
A handle to a connected, connection-oriented socket.
Upvotes: 1