TWSocket.HowTo.Close

From Overbyte
Revision as of 13:40, 26 June 2008 by Markus.humm (talk | contribs) (first entry based on the FAQ)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

> Closing a socket, who, how, when

There are several ways to close (and eventually destroy) a TWSocket. Here is the list: CloseDelayed, Close, ShutDown, Abort, Release, Free, Destroy. The last three are most useful for dynamically-created TWSOCKET objects. Here is a brief explaination of them.


- CloseDelayed

Is in most cases the preferred way. It will post a message to itself to close the TWSocket. This means that the socket closure is done outside the code that calls the CloseDelayed, meaning a while later. The message handler will call Close.


- Close

Attempt to gracefully close the socket. If there is still some data waiting in the buffers it will try to send it. Do not use Close from within any TWSocket events, instead use CloseDelayed.


- ShutDown(1)

Preferred way of closing if you have just sent some data and want to close the socket. It will try to send the data before closing.


- Abort

This is the quick and dirty way of closing. If you have some data in any of the buffers it will probably be lost.


- Release

Similar to CloseDelayed, this method will allow you to destroy a dynamically-created TWSocket from within one of its own events. If the socket is still open it will be closed. The call to Destroy is done with a message handler, so it will be done outside of the event handler.


- Free

For dynamically-created TWSocket. Checks for nil pointer and if it's not it will call Destroy.


- Destroy

For dynamically-created TWSocket. If the socket is not closed it will call Close first.

As you can see by the way these methods work, you have to make a protocol that ensures sent data is received. The simplest way is that the receiver closes the socket after it has received all of the data. Of course the receiver must have some way of knowing when it has received all the data that it is expecting. One approach is to use a simple character or command. The sender can close the socket after the receiver has acknowledged that it has received all of the data. This can be done quite easily if you write a command interpreter and use LineMode (with #13#10 as LineEnd because it makes testing easy with a telnet program). Through simple commands both ends can exchange information. When someone decides to send binary data it tells the receiver. First of all the receiver sets LineMode to False and then informs the sender that it is ok to start sending the data. When the receiver has received all of the data, it can save and/or manipulate it, set LineMode back to True and then inform the sender it is ok to start exchanging commands again.