TWSocket Last Updated: 10/29/2001 |
The base component of ICS. All other components use it. It can be used for own based protocols other than the one provided with ICS. It ecaptulates TCP and UDP and can be used als a client or a server. SOCKS support and Multicast is also provided.
Here are the sections available for the TWSocket:
- [ Properties ]
- [ Events ]
- [ Methods ]
- [ Globals ]
- [ Notes ]
Below is the full description for all the sections in the TWSocket:
Below is a list of all Properties for use as a quick reference:
- Addr
- ComponentOptions
- DnsResult
- DnsResultList
- FlushTimeOut
- LastError
- LineEcho
- LineEdit
- LineEnd
- LineLimit
- LineMode
- LingerOnOff
- LingerTimeout
- LocalAddr
- LocalPort
- MultiThreaded
- MultiCast
- MultiCastAddrStr
- MultiCastIpTTL
- ReuseAddr
- PeerAddr
- PeerPort
- Port
- Proto
- RcvdCount
- ReadCount
- SendFlags
- SocksAuthentication
- SocksLevel
- SocksPassword
- SocksPort
- SocksServer
- SocksUsercode
- Terminated
Below is a list of all Properties with their complete descriptions:
Addr: | Can be a dotted IP address, or a hostname. Preferable is a dotted IP address. For a client it is the machine to connect to, and for a server it is the interface to listen on if it is a multi homed computer. Default value for a server is 0.0.0.0 |
[Return to Top] | |
ComponentOptions: | wsoNoReceiveloop change the behaviour of winsock message processing. Without this option, TWSocket will try to handle messages as fast as possible, looping when necessary. This will impact behaviour on very fast network connection (relative to CPU speed. With very fast connection it is recommended to use this option. wsoTcpNoDelay When doing multiple sends of less than the Maximum Transmission Unit (MTU), you may see poor performance. On an Ethernet network, the MTU for TCP/IP is 1460 bytes. This option tells TCP/IP to send always, regardless of packet size. This will result in sub-optimal use of the physical network, but it will avoid the delay of waiting for an ACK. |
[Return to Top] | |
DnsResult: | Return value of DnsLookup method. See this method for details. See example in OnDnsLookupDone. |
[Return to Top] | |
DnsResultList: | Return values of DnsLookup method. See this method for details. |
[Return to Top] | |
FlushTimeOut: | Not used by the component. You can eventually use this if you override the Flush method. |
[Return to Top] | |
LastError: | Contains winsock's last error. |
[Return to Top] | |
LineEcho: | Set this to True if you write a server where someone talk to it with e.g. Telnet.exe. Setting this to true will have TWSocket echo all characters back to the client. But you will gain much performance if setting it to False. |
[Return to Top] | |
LineEdit: | Same use as for the Line Echo. It will allow the client to use destructive backspace. Same comment about performance as for the Line Echo property. |
[Return to Top] | |
LineEnd: | If you use Line Mode then here you set the character(s) where you wants to terminate each line. Note that the ending characters are included when you receive. Default value is #13#10 |
[Return to Top] | |
LineLimit: | This is for security. Suppose someone will try to blow up your application sending endless lines then this is the limit. If this value is exceeded the OnLineLimitExeeded event is fired. |
[Return to Top] | |
LineMode: | Setting this to true will have OnDataAvailable fired only when a complete line is received. That is when the Line End characters are received. If you set Line Mode to false you have to concatenate all received packets by yourself. |
[Return to Top] | |
LingerOnOff: | The Linger Option will let winsock send his own internal buffer before closing a session. Note that this is not working properly in all OS. swLingerNoSet will skip the setting and let the OS's default value which is wsLingerOff. wsLingerOn will try a gracefully close and try to send data that is still in the send buffer. You can eventually set the Linger Timeout property for it. |
[Return to Top] | |
LingerTimeout: | Max timeout that winsock will try to send data before giving it up if closing and LingerOnOff is set to wsLingerOn. |
[Return to Top] | |
LocalAddr: | If you have a multi homed computer you can use this property to choose the interface. It is intended for a client that will connects to a server. Note that for a server than Addr property has to be used. Default value is 0.0.0.0 |
[Return to Top] | |
LocalPort: | When you connect to a server the OS choose a local port for you. This option will let you choose this port if you wants. |
[Return to Top] | |
MultiThreaded: | Set this to true if you use TWSocket in a thread. Note it has nothing to do with multiple sockets, or a server with multiple clients. |
[Return to Top] | |
MultiCast: | Allow socket to listen on a MultiCast port. |
[Return to Top] | |
MultiCastAddrStr: | The MultiCast (group) IP address to listen on, eg: '225.1.2.3'. Note this must be within the defined multicast address range. |
[Return to Top] | |
MultiCastIpTTL: | The Time To Live of the multicast packet (related to router traversal). |
[Return to Top] | |
ReuseAddr: | Permit multiple windows on the same machine to listen to the MultiCast socket. |
[Return to Top] | |
PeerAddr: | Contains the address of the peer to which a socket is connected. |
[Return to Top] | |
PeerPort: | Contains the local port of the peer to which a socket is connected. |
[Return to Top] | |
Port: | For a server the port where it listens on, for a client the port on the server to connect too. |
[Return to Top] | |
Proto: | Can be 'TCP' or 'udp'. |
[Return to Top] | |
RcvdCount: | Contains the received bytes still in winsock buffer (not yet received). Note that this value is not reliable and can contain zero while there is something to receive. |
[Return to Top] | |
ReadCount: | Contains the count of received bytes in current session. |
[Return to Top] | |
SendFlags: | If you wants to send out of band data, then you have to set this to wsSendUrgand |
[Return to Top] | |
SocksAuthentication: | Set it to SocksAuthenticateUserCode if authentication is required. |
[Return to Top] | |
SocksLevel: | The Socks level that is used on the Proxy. It can be 4 or 5. Mostly 5. |
[Return to Top] | |
SocksPassword: | The authentication password. |
[Return to Top] | |
SocksPort: | The socks port of the fire wall, normally 1080. |
[Return to Top] | |
SocksServer: | The fire wall / socks server host. |
[Return to Top] | |
SocksUsercode: | The socks username. |
[Return to Top] | |
Terminated: | If you use TWSocket in NO FORMS, and you have assigned your own message pump in OnMessagePump, then you have to set Terminated to True if you application terminates. |
[Return to Top] | |
Below is a list of all Events for use as a quick reference:
Below is a list of all Events with their complete descriptions:
OnBgException: | This is fired when a background exception occur. TWSocket works completely in background using corporative multitasking. This means event driven using messages. If some exception should occur form the middle of nowhere (the message pump) then this event is fired.procedure TForm1.WSocket1BgException(Sender: TObject; E: Exception; var CanClose: Boolean); begin CanClose := True; // let's close the connection end; |
[Return to Top] | |
OnChangeState: | TWSocket has several states: wsInvalidState, wsOpened, wsBound, wsConnecting, wsConnected, wsAccepting, wsListening, wsClosed. Every time state is changed this event is fired. You can use it to log or display information.procedure TForm1.WSocket1ChangeState(Sender: TObject; OldState, NewState: TSocketState); const aSocketState: array[TSocketState] of string = ( 'Invalid', 'Opened', 'Bound', 'Connecting', 'Connected', 'Accepting', 'Listening', 'Closed'); begin if not Application.Terminated then Label1.Caption := aSocketState[NewState]; end; |
[Return to Top] | |
OnDataAvailable: | Is called when data is available from winsock. You have to receive all data in here. If you don't receive all data then it is called back immediately after it ends. This event is also called immediately after a connection. If your application has nothing to receive, then you must receive here and trow away, or assign nothing (nil) to this event.procedure TForm1.WSocket1DataAvailable(Sender: TObject; Error: Word); var Count: integer; Rcvd: array[0..8191] of char; begin if Error <> 0 then Exit; with Sender as TWSocket do Count := Receive(@Rcvd[0], High(Rcvd)); if Count <= 0 then Exit; // Here handle the received data end; |
[Return to Top] | |
OnDataSent: | Is called when TWSocket has sent whole his buffer to winsock. This is the place to send the next chuck of data if you have to. Do not confuse this with OnSendData.procedure TForm1.WSocket1DataSent(Sender: TObject; Error: Word); begin if Error <> 0 then Exit; PostMessage(Handle, WM_NEXT_DATA, integer(Sender), 0); end; |
[Return to Top] | |
OnDnsLookupDone: | If you wants to connect to a server and you don't know it's IP address, then it is preferable that you call the DnsLookup method. When it finishes this event is called. Then you have the address in the DnsResult property or if there are several IP addresses in the DnsResult List property. This is the place to fill in the Addr property and Port, and call Connect.procedure TForm1.Button1Click(Sender: TObject); begin with WSocket1 do DnsLookup('ftp.microsoft.com'); end; procedure TForm1.WSocket1DnsLookupDone(Sender: TObject; Error: Word); begin if Error <> 0 then Exit; with Sender as TWSocket do begin Addr := DnsResult; Port := 'ftp'; Connect; end; end; |
[Return to Top] | |
OnError: | If you don't wants to handle exceptions yourself then you can assign code to this event. As a good programming rule however you have to handle your code in a try / except block and handle the exceptions yourself in the except part of it. |
[Return to Top] | |
OnLineLimitExceeded: | Is called when someone try to send you very long lines, and the amount of data exceeds the value in the property Line Limit. You can use it to eventually disconnect the offending client.procedure TForm1.WSocket1LineLimitExceeded(Sender: TObject; RcvdLength: Integer; var ClearData: Boolean); begin with Sender as TWSocket do CloseDelayed; // just trow this client away end; |
[Return to Top] | |
OnLineTooLong: | Not used by the component. You can eventually use it if you override the Read Line method. |
[Return to Top] | |
OnMessagePump: | If you use TWSocket with NO FORMS then you can use either call Message Loop or Process Messages to quickly build a working message pump. Or you may build your own custom message pump tailored to your needs. Your message pump must set TWSocket.Terminated property to TRUE when your application terminates or you may experience long delays when closing your application. You must assign it at run-time before using the component. If there's nothing assigned to it TWSocket will call automatically his own message pump. |
[Return to Top] | |
OnSendData: | Is called every time a packet is sent to winsock. Do not confuse this with OnDataSent. |
[Return to Top] | |
OnSessionAvailable: | For a listening socket this is called when a client connects to it. This is the place to accept a connection. |
[Return to Top] | |
OnSessionClosed: | Is called when the connection is closed. |
[Return to Top] | |
OnSessionConnected: | If you connects to a server then this event is called as soon there is a TCP connection. |
[Return to Top] | |
OnSocksAuthState: | Returns the state of the socks connection. |
[Return to Top] | |
OnSocksConnected: | Returns a successful socks connection. |
[Return to Top] | |
OnSocksError: | Returns a sock error. |
[Return to Top] | |
Below is a list of all Methods for use as a quick reference:
- Importand
- Abort
- Close
- CloseDelayed
- Connect
- Release
- Flush
- WaitForClose
- Listen
- Accept
- Receive
- ReceiveStr
- ReceiveFrom
- PeekData
- Send
- SendTo
- SendStr
- DnsLookup
- ReverseDnsLookup
- CancelDnsLookup
- GetPeerAddr
- GetPeerPort
- GetPeerName
- GetXPort
- GetXAddr
- TimerIsSet
- TimerClear
- TimerCmp
- GetSockName
- SetLingerOption
- Dup
- Shutdown
- Pause
- ReadLine
- Resume
- PutDataInSendBuffer
- PutStringInSendBuffer
- DeleteBufferedData
- MessagePump
- MessageLoop
- ProcessMessage
- ProcessMessages
- ThreadAttach
Below is a list of all Methods with their complete descriptions:
Importand: | All methods of TWSocket are asynchrony. This means non-blocking, they return immediately doing the work in background using corporative multitasking. This means that TWSocket must have a message pump. If you write an application without one you must create one yourself or use the one provided in TWSocket. |
[Return to Top] | |
Abort: | procedure Abort; Quick and dirty way to close a connection. Data in send and receive buffers may get lost. |
[Return to Top] | |
Close: | procedure Close; Closes the connection. Winsock will try to send or receive data in the buffers. |
[Return to Top] | |
CloseDelayed: | procedure CloseDelayed; This closes a connection outside of the procedure where it is called by posting a message. Use this if you want to close a TWSocket from inside of his event handlers. |
[Return to Top] | |
Connect: | procedure Connect; Connect to a remote. You have to assign Addr and Port properties every time before calling it. |
[Return to Top] | |
Release: | procedure Release; Similar to Close Delayed, 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. |
[Return to Top] | |
Flush: | procedure Flush; This method will send the whole TWSocket buffer and returns when it is empty. As it is a synchronized method it its use is discouraged. Do not call this form within event handlers because it calls the message pump in a loop. |
[Return to Top] | |
WaitForClose: | procedure WaitForClose; This method will let TWSocket send and receive but does only return when it closes. As it is a synchronized method it its use is discouraged. Do not call this form within event handlers because it calls the message pump in a loop. |
[Return to Top] | |
Listen: | procedure Listen; Let TWSocket listen (as server). You have to assign Addr and Port properties every time before calling it. |
[Return to Top] | |
Accept: | function Accept: TWSocket; This routine extracts the first incoming connection, creates a new socket and returns a handle to it. You have to use this with the Dup method if you write a server with TWSocket. |
[Return to Top] | |
Receive: | function Receive(Buffer : Pointer; BufferSize: integer) : integer; Call this only in the OnDataAvailable event. It will receive Buffer Size bytes into Buffer. If Buffer Size is <= 0 it will receive nothing. If you have not received all available data then OnDataAvailable will be called again immediately. It returns the actually received bytes. If the return value is <= 0 there is nothing received, you can ignore this safely. Note: return value of 0 is when the remote has gracefully closed. |
[Return to Top] | |
ReceiveStr: | function ReceiveStr : string; This will let you receive data in a string. It calls Receive. |
[Return to Top] | |
ReceiveFrom: | function ReceiveFrom(Buffer: Pointer; BufferSize: Integer; var From: TSockAddr; var FromLen: Integer): integer; Call this only from within the OnDataAvailable event. Use this if you receive with 'udp' protocol. You can also use Receive with 'udp' but then you don't know who sent it. |
[Return to Top] | |
PeekData: | function PeekData(Buffer : Pointer; BufferSize: integer) : integer; The save as Receive, but the data will not be removed from the buffer. It is not encouraged to use this as it is better to Receive to avoid double copy's of the receiving data. |
[Return to Top] | |
Send: | function Send(Data : Pointer; Len : Integer) : integer; Send Data with Len. Note that Len can be much larger than the Maximum Transmission Unit (MTU), TWSocket will buffer it for you. If you have very large amount of data to send, then consider to split it in packets (4 kb give good performance) and send every next packet in the OnDataSent event. |
[Return to Top] | |
SendTo: | function SendTo(Dest: TSockAddr; DestLen: Integer; Data: Pointer; Len: Integer): integer; Use this if you want to send with 'udp' protocol. |
[Return to Top] | |
SendStr: | function SendStr(Str : String) : Integer; Same as Send, but it accepts a string. Internally it calls Send. |
[Return to Top] | |
DnsLookup: | procedure DnsLookup(HostName : String); The preferred way before connect to a remote host. It will start hostname resolution in the background.. When it's done OnDnsLookupDone is fired. If HostName is a valid dotted IP address then OnDnsLookupDone is fired immediately. It will cancel any pending lookup. See example in OnDnsLookupDone. |
[Return to Top] | |
ReverseDnsLookup: | procedure ReverseDnsLookup(HostAddr: String); Given as parameter the dotted IP address of a machine, it will find the hostname in the background. When it's done OnDnsLookupDone is fired. It will cancel any pending lookup. |
[Return to Top] | |
CancelDnsLookup: | procedure CancelDnsLookup; Cancels any pending (reverse) dns lookup. |
[Return to Top] | |
GetPeerAddr: | function GetPeerAddr: string; Returns the address of the peer to which a socket is connected. |
[Return to Top] | |
GetPeerPort: | function GetPeerPort: string; Returns the local port of the peer to which a socket is connected. |
[Return to Top] | |
GetPeerName: | function GetPeerName(var Name: TSockAddrIn; NameLen: Integer): integer; Returns the hostname of the peer to which a socket is connected. |
[Return to Top] | |
GetXPort: | function GetXPort: string; Returns local port to which a socket has been bound. |
[Return to Top] | |
GetXAddr: | function GetXAddr: string; Returns local IP address to which a socket has been bound. |
[Return to Top] | |
TimerIsSet: | function TimerIsSet(var tvp: TTimeVal) : Boolean; Related to timeval handling (see select() winsock API call). Not internally used by ICS. |
[Return to Top] | |
TimerClear: | procedure TimerClear(var tvp: TTimeVal); Related to timeval handling (see select() winsock API call). Not internally used by ICS. |
[Return to Top] | |
TimerCmp: | function TimerCmp(var tvp: TTimeVal; var uvp: TTimeVal; IsEqual: Boolean): Boolean; Related to timeval handling (see select() winsock API call). Not internally used by ICS. |
[Return to Top] | |
GetSockName: | function GetSockName(var saddr: TSockAddrIn; var saddrlen: Integer): integer; Gets the local address of the socket. |
[Return to Top] | |
SetLingerOption: | procedure SetLingerOption; Call SetLingerOption to set the linger option on the fly (the connection must be established to set the option). See winsock.closesocket on line help (winsock.hlp or win32.hlp) for a discussion of this option usage. |
[Return to Top] | |
Dup: | procedure Dup(NewHSocket: TSocket); Assigns an accepted socket handle to TWSocket. Use it together with Accept. |
[Return to Top] | |
Shutdown: | procedure Shutdown(How: Integer); Closes the connection. Set How to 0 to disable both send and receive, 1 to disable receive (winsock will try to send pending data) and 2 to disable send. |
[Return to Top] | |
Pause: | procedure Pause; Pauses the TCP communication until the Resume method is called. Note that calling this methods will reflect on several events to fire. |
[Return to Top] | |
ReadLine: | procedure ReadLine(Timeout: integer; var Buffer: String); It will return when a line is received. This method is meant to be called from outside the OnDataAvailable event. It's a synchronized method and its use is discouraged. Timeout is in seconds if positive, milli-seconds if negative. |
[Return to Top] | |
Resume: | procedure Resume; Resumes a paused TCP session. Note that calling this method will reflect on several events to fire. |
[Return to Top] | |
PutDataInSendBuffer: | procedure PutDataInSendBuffer(Data: Pointer; Len: Integer); This will concatenate data in the send buffer of TWSocket. The data is not sent until Send is called. |
[Return to Top] | |
PutStringInSendBuffer: | procedure PutStringInSendBuffer(Str: String); Same as PutDataInSendBuffer but accepts a string as data. |
[Return to Top] | |
DeleteBufferedData: | procedure DeleteBufferedData; This will remove any data from the internal output buffer of TWSocket. |
[Return to Top] | |
MessagePump: | procedure MessagePump; Calling this method will fire OnMessagePump if assigned, or will call his own Process Messages if not assigned |
[Return to Top] | |
MessageLoop: | procedure MessageLoop; You can use this to quickly build a working message pump. It loop tru message processing until the WM_QUIT message is received. This is intended for multithreaded application using TWSocket. MessageLoop is different from ProcessMessages because it actually block if no message is available. The loop is broken when WM_QUIT is retrieved. |
[Return to Top] | |
ProcessMessage: | function ProcessMessage: Boolean; This function is very similar to TApplication.ProcessMessage. You can also use it if your application has no TApplication object (Forms unit not referenced at all). |
[Return to Top] | |
ProcessMessages: | procedure ProcessMessages; You can use this to quickly build a working message pump. It loop thru message processing until all messages are processed. This function is very similar to TApplication.ProcessMessage. This is intended for multithreaded application using TWSocket. You can also use it if your application has no TApplication object (Forms unit not referenced at all). |
[Return to Top] | |
ThreadAttach: | procedure ThreadAttach Attach an already created TWSocket to the current thread. It creates a hidden window. Note that you have to call this in the Execute method of the thread. If you do not the current thread will be the main thread. |
[Return to Top] | |
Below is a list of all Globals for use as a quick reference:
Below is a list of all Globals with their complete descriptions:
WinsockInfo: | function WinsockInfo: TWSADATA; Returns the system description of winsock. |
[Return to Top] | |
WSocketErrorDesc: | function WSocketErrorDesc(error: integer): string; Translates the winsock error codes into a human readable string. |
[Return to Top] | |
WSocketGetHostByAddr: | function WSocketGetHostByAddr(Addr : String): PHostEnt; Gets host information corresponding to an address. |
[Return to Top] | |
WSocketGetHostByName: | function WSocketGetHostByName(Name : String): PHostEnt; Gets host information corresponding to the host name. |
[Return to Top] | |
LocalHostName: | function LocalHostName: String; Return the local host name. |
[Return to Top] | |
LocalIPList: | function LocalIPList: TStrings; Returns a TStringList with all the addresses of the local adaptors. |
[R |