Have you copied the example? (I haven't looked it up.) Surely not! On the face of it you seem to loop until there is input and then close the port. It is expecting a bit much for the event to fire and capture the input while (sort of at the same time) closing the port.
How about taking a copy of the example and building it up to do what you want, checking it still works at each stage? (This is the cautious approach I have used in the past!)
HTH, Mike.