Updated socket code to better handle graceful and ungraceful disconnections