I believe you should try the existing solutions first before you start programming your own. One (reportedly very good) chat server is
. It is pretty much customizable, and extendable (with perl too). It uses an open XML based protocol so you can write your own clients for it with ease. Usually the chat server is running all the time as a daemon - I don't understand why you want to start it from the client.