sockets, timers, and their cleanup

I want to do some actions with a remote host, should only take a second or two. When all is complete, I expect to issue socket.close() to clean up. So, when is the socket actually destroyed? The Notes for SocketCore.Close() indicate that some information remains after close() but doesn’t say when the socket will go away. This seems to imply that the socket stays around and could in principle be re-opened.

Second, I want to protect this sequence with a timer. After all, the remote process could get wedged in the middle of the data exchange sequence and simply cease sending data but with the connection remaining in good shape. Then, no further event will fire on my side, so the user is left wondering WTF is going on.

I thought to subclass the timer and keep a reference to the socket in my timer subclass instance. Then, if the timer goes off I can close the socket and give the user a message. Equally, as I’m already subclassing the socket, I will keep a reference to the timer, so that in the good case I can not only close the socket, but de-activate the timer also. Does it suffice to just set the two references to Nil (either in the timer action event or when the socket event handler decides to close the socket)? When does the timer instance get removed?

Xojo uses reference counting. As soon as the last reference is dropped, and the count goes to zero, the object is destroyed. It happens on the line of code that sets the reference to nil.

Sounds like I’d better do:


socket.close ()
socket = Nil

Is that a fair summary?

yes, thats right. Make sure there aren’t any other objects with references to it, possibly that were talking through it, or if it was passing it’s data off to other objects make sure it doesn’t keep a reference to any of them. Otherwise the reference count won’t ever reach 0 and they will never be cleaned up. If you’re not doing any of that and it’s all just handled in a socket subclass then thats all you need to do.

Thanks, and TimH, too. Hmmm, this gets more and more like JavaScript by the minute.

Hmmm again, thinking about it a bit more:

Where the socket and timer are created, those go out of scope at the end of the method. As in:

s = new mysocket t = new mytimer

s and t go out of scope, but the socket and the timer live on. I read some doc that indicated that the socket, at least, is treated specially so that this happens. In order for the reference to reach zero, is it the case that in the event handlers, the argument passed to them (such as t as timer) is passed byref so that doing t = Nil is able to drop the ref count because it’s not my local copy of t ?

Sockets keep a self-reference while they are connected. This prevents their reference count from reaching zero even if no other references exist. Explicitly disconnect/close the socket before going out of scope to guarantee timely destruction.