{ GPC demo program for the Socket unit (client or server side)

  Copyright 2002-2006 Frank Heckenbach <frank@pascal.gnu.de>

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License as
  published by the Free Software Foundation, version 2.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; see the file COPYING. If not, write to
  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  Boston, MA 02111-1307, USA.

  As a special exception, if you incorporate even large parts of the
  code of this demo program into another program with substantially
  different functionality, this does not cause the other program to
  be covered by the GNU General Public License. This exception does
  not however invalidate any other reasons why it might be covered
  by the GNU General Public License. }

{$gnu-pascal,I+}
{$if __GPC_RELEASE__ < 20041017}
{$error This unit requires GPC release 20041017 or newer.}
{$endif}

program ClientServerDemo;

uses GPC, Socket;

const
  Port = 9755;

var
  HostAddress, HostName, s: TString;
  SI, SO, FI, FO: Text;

procedure InitServerSocket;
var Error: TString;
begin
  OpenStreamSocket (nil, Port, SI, SO, Error);
  if Error <> '' then
    begin
      WriteLn (StdErr, ParamStr (0), ': ', Error);
      RestoreTerminal (True);
      Halt (1)
    end
end;

procedure SocketConnection;
begin
  if not AcceptConnection (SI, FI, FO, HostAddress, HostName, Null) then
    begin
      WriteLn (StdErr, ParamStr (0), ': ', 'Error while accepting connection');
      RestoreTerminal (True);
      Halt (1)
    end
end;

procedure OpenClientSocket (const Host: String);
var Error: TString;
begin
  OpenStreamSocket (Host, Port, FI, FO, Error);
  if Error <> '' then
    begin
      WriteLn (StdErr, ParamStr (0), ': ', Error);
      RestoreTerminal (True);
      Halt (1)
    end
end;

begin
  WriteLn ('Server (press just enter) or client (enter server host)? ');
  ReadLn (s);
  if s = '' then
    begin
      WriteLn ('Waiting for connection on port ', Port, ' ...');
      InitServerSocket;
      SocketConnection;
      WriteLn ('Connection from ', HostName);
      while not EOF (FI) do
        begin
          ReadLn (FI, s);
          WriteLn (FO, 'You wrote: ', s);
          WriteLn ('Client wrote: ', s)
        end
    end
  else
    begin
      OpenClientSocket (s);
      WriteLn (FO, 'clientdemo');
      repeat
        ReadLn (FI, s);
        WriteLn (s)
      until not CanRead (FI)
    end;
  Close (FI);
  Close (FO)
end.
