code cleanup and refactored to support multiple sockets