Privacy Policy

Blog italiano

Clicca qui se vuoi andare al blog italiano su Lazarus e il pascal.

Forum ufficiale

Se non siete riusciti a reperire l'informazione che cercavate nei nostri articoli o sul nostro forum vi consiglio di visitare il
Forum ufficiale di Lazarus in lingua inglese.

Lazarus 1.0

TDD o Test-Driven Development
immagine docker per lavorare con lazarus e free pascal
Indice
Installare lazarus su mac osx sierra
Un dialog per la connessione al database:TfmSimpleDbConnectionDialog
Superclasse form base per programmi gestionali (e non) #4 - wait animation
Superclasse form base per programmi gestionali (e non) #3 - traduzione delle form
Superclasse form base per programmi gestionali (e non) #2 - log, exception call stack, application toolbox
Superclasse form base per programmi gestionali (e non)
Advanced Record Syntax: un esempio pratico
DB concetti fondamentali e TDBEdit, TDBMemo e TDBText
DB concetti fondamentali e DBGrid
Advanced Record Syntax
DB concetti fondamentali e ZeosLib
DB concetti fondamentali e connessioni standard
guida all'installazione di fpc trunk da subversion in linux gentoo
Creare un server multithread
Cifratura: breve guida all'uso dell'algoritmo BlowFish con lazarus e free pascal.
Free Pascal e Lazarus sul Raspberry Pi
fpcup: installazioni parallele di lazarus e fpc
Ubuntu - aggiornare free pascal e lazarus
Come interfacciare periferica twain
Lazarus 1.0
Aspetto retrò (Cmd Line)
Disporre le finestre in un blocco unico (come Delphi)
Zeos ... dietro le quinte (prima parte)
Lavorare con file in formato JSON con Lazarus
Overload di operatori
Dataset virtuale
Linux + Zeos + Firebird
Pascal Script
La gestione degli errori in Lazarus
Indy 10 - Invio email con allegati
Brute force
Le permutazioni
Da DataSource a Excel
StatusBar - aggirare l'errore variabile duplicata
Visualizzare un file Html esterno
Evidenziare voci TreeView
Toolbar
Direttiva $macro
Indy gestiore server FTP lato Client
TImage su Form e Panel
PopUpMenu sotto Pulsante (TSpeedButton)
Conversione numerica
Proprietà
Funzioni a parametri variabili
Overload di funzioni
Liste e puntatori
Conferma di chiusura di un applicazione
Il file: questo sconosciuto
UIB: Unified Interbase
System Tray con Lazarus
Intercettare tasti premuti
LazReport, PDF ed immagini
Lazarus e la crittografia
Ampliare Lazarus
Generare controlli RUN-TIME
TTreeview e Menu
TTreeView
Utilizzare Unità esterne
Lavorare con le directory
Realizzare programmi multilingua
Codice di attivazione
File INI
Esempio lista in pascal
Stabilire il sistema operativo
Recuperare codice HTML da pagina web
Trascinare un file nel programma
Mandare mail con Lazarus
Welcome to Italian community of Lazarus and Free Pascal. Please login or sign up.

Recenti

How To

Utenti
Stats
  • Messaggi totali: 20.586
  • Totale discussioni: 2.472
  • Online today: 140
  • Online ever: 5.949 (Luglio 30, 2026, 09:49:59 PM)
Utenti online
  • Users: 0
  • Guests: 10
  • Total: 10
10 Visitatori, 0 Utenti
Con questo articolo vedremo come realizzare un semplice socket server, utilizzando le librerie synapse.
Diamo per scontato che abbiamo installato e configurato tali librerie.
Apriamo Lazarus e creiamo una nuova applicazione console che salveremo con il nome "serverSock" e andiamo a sostituire le unit presenti con le seguenti


uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Classes, SysUtils, CustApp, echo, Unit_Operazioni
  { you can add units after this };


poi successivamente cerchiamo il pezzo di codice

  { add your program here }


e sotto aggiungiamo

  app:=TTCPEchoDaemon.create;
  app.Execute;
  // stop program loop
  Terminate;


Quindi la nostra applicazione risulterà la seguente


program serverSock;

{$mode objfpc}{$H+}

uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Classes, SysUtils, CustApp, echo, Unit_Operazioni
  { you can add units after this };

type

  { TMyServer }

  TMyServer = class(TCustomApplication)
  protected
    procedure DoRun; override;
  public
    constructor Create(TheOwner: TComponent); override;
    destructor Destroy; override;
    procedure WriteHelp; virtual;
  end;

{ TMyServer }

procedure TMyServer.DoRun;
var
  ErrorMsg: String;
  app: TTCPEchoDaemon;
begin
  // quick check parameters
  ErrorMsg:=CheckOptions('h','help');
  if ErrorMsg'' then begin
    ShowException(Exception.Create(ErrorMsg));
    Terminate;
    Exit;
  end;

  // parse parameters
  if HasOption('h','help') then begin
    WriteHelp;
    Terminate;
    Exit;
  end;

  { add your program here }
  app:=TTCPEchoDaemon.create;
  app.Execute;
  // stop program loop
  Terminate;
end;

constructor TMyServer.Create(TheOwner: TComponent);
begin
  inherited Create(TheOwner);
  StopOnException:=True;
end;

destructor TMyServer.Destroy;
begin
  inherited Destroy;
end;

procedure TMyServer.WriteHelp;
begin
  { add your help code here }
  writeln('Usage: ',ExeName,' -h');
end;

var
  Application: TMyServer;
begin
  Application:=TMyServer.Create(nil);
  Application.Title:='My Server Test';
  Application.Run;
  Application.Free;
end.


Successivamente andiamo a creare le seguenti unit


unit echo;

interface

uses
  Classes, blcksock, synsock, sysutils, users,  baseunix, Unit_Operazioni;

type
  TTCPEchoDaemon = class(TThread)
  private
    Sock:TTCPBlockSocket;
  public
    Constructor Create;
    Destructor Destroy; override;
    procedure Execute; override;
  end;

  TTCPEchoThrd = class(TThread)
  private
    Sock:TTCPBlockSocket;
    CSock: TSocket;
  public
    Constructor Create (hsock:tSocket);
    procedure Execute; override;
  end;

implementation

{ TEchoDaemon }

Constructor TTCPEchoDaemon.Create;
begin
  inherited create(false);
  sock:=TTCPBlockSocket.create;
  FreeOnTerminate:=true;
end;

Destructor TTCPEchoDaemon.Destroy;
begin
  Sock.free;
end;

procedure TTCPEchoDaemon.Execute;
var
  ClientSock:TSocket;
  Porta: string;
  Host: string;
begin
  Porta:='2408';
  Host:='0.0.0.0';
  with sock do
    begin
      CreateSocket;
      setLinger(true,10000);
      bind(Host,Porta);
      listen;
      repeat
        if terminated then break;
        if canread(1000) then
          begin
            ClientSock:=accept;
            if lastError=0 then TTCPEchoThrd.create(ClientSock);
          end;
      until false;
    end;
end;

{ TEchoThrd }

Constructor TTCPEchoThrd.Create(Hsock:TSocket);
begin
  inherited create(false);
  Csock := Hsock;
  FreeOnTerminate:=true;
end;

procedure TTCPEchoThrd.Execute;
var
  s: string;
begin
  sock:=TTCPBlockSocket.create;
  try
    Sock.socket:=CSock;
    sock.GetSins;
    with sock do
      begin
        repeat
          if terminated then break;
          s := RecvPacket(60000);
          //devo eliminare i caratteri di andata a capo, altrimenti sono
          //nella stringa letta e non riesco a fare i controlli
          s:=stringReplace(s, #13 , '', [RfReplaceAll]);
          s:=stringReplace(s, #10 , '', [RfReplaceAll]);
          if lastError0 then break;

          if s='GETDATE' then
          begin
               GetDate(sock);
          end
          else if s='GETHOUR' then
          begin
               GetHour(sock);
          end
          else if s='GETMENU' then
          begin
               GetMenu(sock);
          end
          else
          begin
               SendString('Comando non valido: ' + s + System.LineEnding);
               SendString('Comandi validi: ' + System.LineEnding);
               SendString('GETDATE' + System.LineEnding);
               SendString('GETHOUR' + System.LineEnding);
               SendString('GETMENU' + System.LineEnding);
          end;
          writeln(Sock.GetRemoteSinIP + ': '+ IntToStr(Sock.GetRemoteSinPort) + ' (' + IntToStr(Self.ThreadID) + ')--> ' + s);

          if lastError0 then break;
        until false;
      end;
  finally
    Sock.Free;
  end;
end;

end.


Per prima cosa andiamo ad impostare i dati essenziali per la messa online del server e quindi cerchiamo le seguenti righe

  Porta:='2408';
  Host:='0.0.0.0';

e modifichiamole come più ci aggrada. In seconda battuta prendiamo atto che la procedura da personalizzare in funzione delle nostre esigenze ha il seguente nome:

procedure TTCPEchoThrd.Execute;

All'interno di tale procedura notiamo che la prima cosa che si fa è mettersi in ascolto in attesa di una stringa, alla quale andiamo ad eliminare i caratteri tipici del tasto "INVIO" o "ENTER"

          s := RecvPacket(60000);
          //devo eliminare i caratteri di andata a capo, altrimenti sono
          //nella stringa letta e non riesco a fare i controlli
          s:=stringReplace(s, #13 , '', [RfReplaceAll]);
          s:=stringReplace(s, #10 , '', [RfReplaceAll]);


Successivamente troviamo il seguente codice:


          if s='GETDATE' then
          begin
               GetDate(sock);
          end
          else if s='GETHOUR' then
          begin
               GetHour(sock);
          end
          else if s='GETMENU' then
          begin
               GetMenu(sock);
          end
          else
          begin
               SendString('Comando non valido: ' + s + System.LineEnding);
               SendString('Comandi validi: ' + System.LineEnding);
               SendString('GETDATE' + System.LineEnding);
               SendString('GETHOUR' + System.LineEnding);
               SendString('GETMENU' + System.LineEnding);
          end;


Che ha lo scopo di interpretare il comando ricevuto precedentemente, nel caso il comando coincida con GETDATE o con GETTIME o GETMENU allora il server effettua l'operazione corrispondente, diversamente il server ritorna al client (che può essere anche una sessione telnet) la lista dei comandi validi.
Poi troviamo la seguente riga


writeln(Sock.GetRemoteSinIP + ': '+ IntToStr(Sock.GetRemoteSinPort) + ' (' + IntToStr(Self.ThreadID) + ')--> ' + s);


che ha lo scopo di scrivere sullo standard output del server l'indirizzo ip del client seguito dal numero di porta, dall'identificativo del thread  che può essere usato come identificativo di sessione e poi il comando ricevuto dal client.

In ultima battuta creiamo la seguente unit

unit Unit_Operazioni;

{$mode objfpc}{$H+}

interface

uses
  Classes, blcksock, synsock, sysutils, users,  baseunix ;

  procedure GetDate(var sock: TTCPBlockSocket);
  procedure GetHour(var sock: TTCPBlockSocket);
  procedure GetMenu(var sock: TTCPBlockSocket);
implementation

procedure GetDate(var sock: TTCPBlockSocket);
begin
     with sock do
     begin
          SendString(DateToStr(Date) + System.LineEnding);
     end;
end;

procedure GetHour(var sock: TTCPBlockSocket);
begin
  with sock do
  begin
     SendString(TimeToStr(Time) + System.LineEnding);
  end;
end;

procedure GetMenu(var sock: TTCPBlockSocket);
begin
  with sock do
  begin
     SendString('-------------------------------------' + System.LineEnding);
     SendString('|    PROVA DI UN                           |' + System.LineEnding);
     SendString('|           SEMPLICE                         |' + System.LineEnding);
     SendString('|                   MENU                        |' + System.LineEnding);
     SendString('|                       !!!                         |' + System.LineEnding);
     SendString('-------------------------------------' + System.LineEnding);
  end;
end;

end.

Quest'ultima unit contiene il codice che risponde ai comandi validi del server, con GETDATE inviamo al client la data attuale sul server, con GETTIME inviamo l'ora e con GETMENU inviamo un simil menù con aspetto retrò.

Per far funzionare il tutto dobbiamo

Progetto -> Opzioni progetto -> Varie

e in Opzioni Personalizzate inseriamo la seguente stringa: -dUseCThreads

Ora compiliamo, e avviamo l'eseguibile dal Terminale/Console/Prompt, poi avviamo un altro Terminale/Console/Prompt e digitiamo (nel caso Host e Porta non siamo cambiati) il comando: telnet localhost 2408
Ovviamente se cambiate il numero di porta agite di conseguenza nel parametrizzare la sessione telnet.
Share on Facebook!Share on Twitter!RedditDigg this story!Del.icio.usStumbleUpon

Comments: 0 *

You don't have permission to comment, or comments have been turned off for this article.

Articles in « Lazarus 1.0 »

Disclaimer:

Questo blog non rappresenta una testata giornalistica poiché viene aggiornato senza alcuna periodicità. Non può pertanto considerarsi un prodotto editoriale ai sensi della legge n. 62/2001.