TTcpServer (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the use of TTcpServer to receive a buffer (in this case, a stream) and to process it. This example can be used with the example for TTcpClientSendStream_(Delphi).

To build this example, create a VCL Forms Application. Add three buttons (Connect, Disconnect, Clear), a memo box, and a TTcpServer from the Tool Palette.

Code

Define the default port for the communication.

const DEFAULT_PORT = 2501;//The default port for the communication

Add the code below to the OnClick event of the 'Connect' button.

procedure TForm3.Button1Click(Sender: TObject);
begin
  //Connecting the server
  TcpServer1.Active := true;
end;

Add the code below to the OnClick event of the 'Disconnect' button.

procedure TForm3.Button2Click(Sender: TObject);
begin
  //Disconnecting the server
  TcpServer1.Active := false;
end;

Add the code below to the OnClick event of the 'Clear' button.

procedure TForm3.Button3Click(Sender: TObject);
begin
  //Clearing the memo
  Memo1.Lines.Clear;
end;

An the code below to the OnCreate event handler of the form.

procedure TForm3.FormCreate(Sender: TObject);
begin
  Memo1.Lines.Clear;

  //Server initialization
  TcpServer1 := TTcpServer.Create(Self);
  TcpServer1.OnAccept := TCpServer1Accept;
  TcpServer1.OnCreateHandle := TcpServer1CreateHandle;
  TcpServer1.OnDestroyHandle := TcpServer1DestroyHandle;
  TcpServer1.LocalPort := IntToStr(DEFAULT_PORT);
end;

Add the code below to the OnAccept event handler of the TTcpServer.

procedure TForm3.TcpServer1Accept(Sender: TObject;
  ClientSocket: TCustomIpClient);
var
  a : array[0..9] of byte;
  I : Cardinal;
begin
//Receives the message from the client
  ClientSocket.ReceiveBuf(a,10,0);
  Memo1.Lines.Add(DateTimeToStr(now) + ' Data added with ' +
                  IntToStr(a[9]));
  for I := 0 to 8 do
  begin
    Memo1.Lines.Add(IntToStr(a[I] + a[9]));
  end;
  Memo1.Lines.Add('--------------------');

end;

Add the code below to the OnCreateHandle event handler of the TTcpServer.

procedure TForm3.TcpServer1CreateHandle(Sender: TObject);
begin
  Memo1.Lines.Add(DateTimeToStr(now) + ' Server started ');
end;

Add the code below to the OnDestroyHandle event handler of the TTcpServer.

procedure TForm3.TcpServer1DestroyHandle(Sender: TObject);
begin
  if Self.Memo1 <> nil then
    Memo1.Lines.Add(DateTimeToStr(now) + ' Server stopped ');
end;

Uses

  • Web.Win.Sockets.TTcpServer ( fr | de | ja )
  • Web.Win.Sockets.TBaseSocket.ReceiveBuf ( fr | de | ja )
  • Web.Win.Sockets.TCustomTcpServer.OnAccept ( fr | de | ja )
  • Web.Win.Sockets.TBaseSocket.OnCreateHandle ( fr | de | ja )
  • Web.Win.Sockets.TBaseSocket.OnDestroyHandle ( fr | de | ja )
  • Web.Win.Sockets.TIpSocket.LocalPort ( fr | de | ja )