program project1;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
Classes, SysUtils, CustApp, blcksock
{ you can add units after this };
type
{ TMyApplication }
TMyApplication = class(TCustomApplication)
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
procedure RunCode(myClient, myPort: string);
procedure OnStatus(Sender: TObject; Reason: THookSocketReason; const Value: String);
end;
{ TMyApplication }
procedure TMyApplication.DoRun;
var
ErrorMsg : String;
client1 : string;
myport : string;
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 }
write('Insert remote ip:');
readln(client1);
write('Insert myport:');
readln(myport);
RunCode(client1, myport);
// stop program loop
Terminate;
end;
constructor TMyApplication.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
end;
destructor TMyApplication.Destroy;
begin
inherited Destroy;
end;
procedure TMyApplication.WriteHelp;
begin
{ add your help code here }
writeln('Usage: ', ExeName, ' -h');
end;
procedure TMyApplication.RunCode(myClient, myPort: string);
var
sock1: TUDPBlockSocket;
Value: ansistring;
begin
sock1 := TUDPBlockSocket.Create;
sock1.OnStatus := @OnStatus;
sock1.CreateSocket;
sock1.bind('0.0.0.0', myPort);
sock1.Connect(myClient, myPort);
while True do
begin
Value := 'Hello : ' + myClient;
sock1.SendString(Value + #13 + #10);
writeln('send: ' + Value);
if sock1.CanRead(1000) then
begin
Value := sock1.RecvString(500);
writeln('recv[' , sock1.GetRemoteSinIP, ':', sock1.GetRemoteSinPort , ']: ' + Value);
sock1.SendString('WE HAVE CONTACT' + #13 + #10);
if Value = 'WE HAVE CONTACT' then break;
end;
end;
sock1.Free;
end;
procedure TMyApplication.OnStatus(Sender: TObject; Reason: THookSocketReason;
const Value: String);
var
sReason : String;
begin
case Reason of
HR_ResolvingBegin : sReason := 'HR_ResolvingBegin';
HR_ResolvingEnd : sReason := 'HR_ResolvingEnd';
HR_SocketCreate : sReason := 'HR_SocketCreate';
HR_SocketClose : sReason := 'HR_SocketClose';
HR_Bind : sReason := 'HR_Bind';
HR_Connect : sReason := 'HR_Connect';
HR_CanRead : sReason := 'HR_CanRead';
HR_CanWrite : sReason := 'HR_CanWrite';
HR_Listen : sReason := 'HR_Listen';
HR_Accept : sReason := 'HR_Accept';
HR_ReadCount : sReason := 'HR_ReadCount';
HR_WriteCount : sReason := 'HR_WriteCount';
HR_Wait : sReason := 'HR_Wait';
HR_Error : sReason := 'HR_Error';
end;
writeln(sReason + ' ' + Value);
end;
var
Application: TMyApplication;
begin
Application:=TMyApplication.Create(nil);
Application.Title:='My Application';
Application.Run;
Application.Free;
end.