At the time, tried to solve a similar problem. Nothing good ever came of it: the connection is permanently torn or hung. In principle, memory problems should not be. If they are, you can restart the script after a certain period of time, it's not scary.
\r
I would advise to learn one of the higher-level languages (e.g. Python or Ruby). To learn Ruby at the primary level is a matter of one day, and the problem it solved much easier.