Added socket flush and refactoring