updated code to detect whether socket is still connected.