the proper way to detect a closed connection is to check socket_last_error.
Connection reset by peer is 104 (either use socket_strerror or don't suppress errors for the time being to find these out), sooo.
while($buffer=@socket_read($sock,512,PHP_NORMAL_READ)){
echo $buffer;
}
if(socket_last_error($sock) == 104) {
echo "Connection closed";
}