Refactor writing to socket a little