exit loop if an error occurred when writing to stream

I need to know when the client has disconnected to stop feeding events to the channel, but it seems that the loop in question will only exit when the channel is closed... kind of a chicken and egg problem. This patch fixes that.