Delphi has a ClientSocket component which supports a client
connection to a server. This is contained in the Internet
palette. An example of a client socket added to a form is
shown in Figure 1.
Figure 1:
In the example in Figure 1 the following code can be used
to make a connection to a server:
Connections from client
to server
procedure
TForm1.Button1Click(Sender: TObject);
var port:integer;
begin
port:=StrToInt(edit4.text);
ClientSocket.Port:=port;
ClientSocket.Host:=edit3.text;
ClientSocket.ClientType:=ctNonBlocking;
ClientSocket.Active:=true;
end;
Initially the properties are set for the socket connection,
such as the port, and the server address. Finally the active
property is set, which causes the client to connect to the
server. When the client detects a connection the Connection
event occurs:
The Socket variable contains the information on the connection,
such as the LocalAddress, LocalHost, LocalPort, RemoteAddress,
RemoteHost and RemoteAddress.
When the code is ready to be send the following can be
used to take the text from the Edit text box and send it
over the socket.
The SendText method is used to send the text over the connected
socket. Figure 2 shows an example of some of the properties
and routines associated with sockets. Also, in this example,
the ASCII characters for Line Feed (10) and Carriage Return
(13) are sent to force a new line on the server.
When data arrives over the socket the Read event is called
(with the information on the socket passed in the Socket
parameter). The ReceiveText property can then be used to
read the data from the socket (as illustrated in Figure
3):
Receiving data from the
server
procedure
TForm1.ClientSocketRead(Sender: TObject;
Socket: TCustomWinSocket);
begin
Memo2.Lines.Add(Socket.ReceiveText);
end;