Assuming you haven't sent a Connection Keep-Alive, you can check ON SOCKCLOSE to test if your socket is done processing.

That means the only code you need is:

Code:
on *:SOCKREAD:contactlist:sockread &binvar | bwrite contacts.xml -1 -1 &binvar