- Код: Выделить всё
program synudp;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes,
blcksock;
const
CONST_PORT = '32000';
type
TUDPThread = class( TThread )
private
function GetLog: String;
procedure OnStatus(Sender: TObject; Reason: THookSocketReason; const Value: string);
protected
m_Log : TStringList;
m_pSocket : TUDPBlockSocket;
public
constructor Create; virtual;
destructor Destroy; override;
property Log : String read GetLog;
end;
TUDPServer = class( TUDPThread )
protected
procedure Execute; override;
end;
TUDPClient = class( TUDPThread )
protected
procedure Execute; override;
end;
{ TUDPThread }
constructor TUDPThread.Create;
begin
inherited Create( false );
FreeOnTerminate := false;
m_Log := TStringList.Create;
m_pSocket := TUDPBlockSocket.Create;
m_pSocket.OnStatus := @OnStatus;
end;
destructor TUDPThread.Destroy;
begin
FreeAndNil( m_pSocket );
FreeAndNil( m_Log );
inherited;
end;
function TUDPThread.GetLog: String;
begin
Result := m_Log.Text;
end;
procedure TUDPThread.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;
m_Log.Add( sReason + ': ' + Value );
end;
{ TUDPServer }
procedure TUDPServer.Execute;
var
sResult : String;
begin
m_pSocket.Bind( cAnyHost, CONST_PORT );
if ( m_pSocket.LastError = 0 ) then
repeat
sResult := m_pSocket.RecvPacket( -1 );
m_Log.Add( sResult );
until terminated or ( sResult = 'exit' );
end;
{ TUDPClient }
procedure TUDPClient.Execute;
var
ii : Integer;
begin
m_pSocket.Connect( cLocalhost, CONST_PORT );
for ii := 0 to 3 do
begin
m_pSocket.SendString( IntToStr( ii ) );
Sleep( 100 );
end;
m_pSocket.SendString( 'exit' );
end;
var
pClient : TUDPClient;
pServer : TUDPServer;
begin
pServer := TUDPServer.Create;
try
Sleep( 100 );
pClient := TUDPClient.Create;
try
pServer.WaitFor;
WriteLn( '*************** Client ***************' );
WriteLn( pClient.Log );
WriteLn( '*************** Server ***************' );
WriteLn( pServer.Log );
ReadLn;
finally
FreeAndNil( pClient );
end;
finally
FreeAndNil( pServer );
end;
end.