/// <summary> /// Closes the socket if it is open or listening. /// </summary> public void Close() { if (closing || Parent.State == State.Closed) { return; } closing = true; try { var oldState = Parent.State; if (oldState == State.Connected || oldState == State.Listening) { Parent.ChangeState(State.Closing); if (socketStream != null) { socketStream.Dispose(); // Should take care of MOST instances, this Dispose also closes the socket. } else if (socket != null && oldState == State.Listening) { socket.Close(); // Listeners don't create a stream, so this handles those } else if (socket != null && socket.IsConnected) { // Edge cases and errors could potentially leave us with a connected socket but without a stream. socket.Shutdown(SocketShutdown.Both); socket.Close(); } socketStream = null; socket = null; } Parent.ChangeState(State.Closed); if (oldState == State.Connected) { Parent.OnDisconnected(); } } catch (Exception ex) { Parent.OnErrorReceived(Parent, ex.AsEventArgs()); } finally { closing = false; } }