fix several bugs relating to socket locking and add a timeout