unit TTcpServerAdd;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Sockets;

type
  TForm3 = class(TForm)
    Button2: TButton;
    Memo1: TMemo;
    TcpServer1: TTcpServer;
    Button1: TButton;
    Button3: TButton;
    procedure FormCreate(Sender: TObject);
    procedure TcpServer1Accept(Sender: TObject;
      ClientSocket: TCustomIpClient);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure TcpServer1CreateHandle(Sender: TObject);
    procedure TcpServer1DestroyHandle(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form3: TForm3;

implementation

// BeginExample: TTcpServer
// Class: Sockets.TTcpServer
// Method: Sockets.TBaseSocket.ReceiveBuf
// Event: Sockets.TCustomTcpServer.OnAccept
// Event: Sockets.TBaseSocket.OnCreateHandle
// Event: Sockets.TBaseSocket.OnDestroyHandle
// Property: Sockets.TIpSocket.LocalPort

// BeginCode
{
This example demonstrated the use of TTcpServer in order to receive
a buffer (stream) and process it. It is to be used with the example
from TTcpClient section.
}

const DEFAULT_PORT = 2501;

{$R *.dfm}

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

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

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

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;

procedure TForm3.TcpServer1Accept(Sender: TObject;
  ClientSocket: TCustomIpClient);
var
  a : array[0..9] of byte;
  I : Cardinal;
begin

  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;

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

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

end.
