type TGalSocketServer =
Class(TObject)
type OnCallBack =
procedure of object;
private
//Definition aller Delagaten
MyAcceptDelegate: AsyncCallback;
MyReadDataDelegate: AsyncCallback;
ServerSocket: Socket;
Port: Integer;
ActiveState: Boolean;
localEndPoint: IPEndPoint;
ipHostInfo: IPHostEntry;
localipAddress: IPAddress;
procedure AcceptCallBack(ar: IAsyncResult);
public
OnConnect: OnCallBack;
property active: Boolean
read ActiveState;
property OnClientConnect: OnCallBack
write OnConnect;
procedure open;
procedure close;
constructor create(pPort: Integer = 5024);
destructor destroy;
override;
end;
constructor TGalSocketServer.create(pPort: Integer = 5024);
begin
inherited create;
Port := pPort;
//Ermitlung des Hostdaten
ipHostInfo := Dns.Resolve(Dns.GetHostName);
localipAddress := ipHostInfo.AddressList[0];
localEndPoint := IPEndPoint.Create(localipAddress, Port);
//Erstellung eines Sockets
ServerSocket := Socket.Create(localEndPoint.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
//initialiesierung aller Delegaten
MyAcceptDelegate := Self.AcceptCallBack;
MyReadDataDelegate :=
Nil;
OnConnect :=
Nil;
end;
{konstruktor}
destructor TGalSocketServer.Destroy;
begin
ServerSocket.Free;
localEndPoint.Free;
ipHostInfo.Free;
localipAddress.Free;
inherited Destroy;
end;
{Mit dieser prozedur wird der Sever gestartet und der Port überwacht}
procedure TGalSocketServer.open;
begin
ServerSocket.Bind(localEndPoint);
ServerSocket.Listen(100);
ServerSocket.BeginAccept(Self.AcceptCallBack,
ServerSocket);
end;
procedure TGalSocketServer.close;
begin
if not ActiveState
then
Exit;
ServerSocket.Shutdown(SocketShutdown.Both);
ServerSocket.Close;
end;
procedure TGalSocketServer.AcceptCallBack(ar: IAsyncResult);
var Listener,
Handle: Socket;
begin
Listener := Socket(ar.AsyncState);
handle := Listener.EndAccept(ar);
if Assigned(OnConnect)
then
OnConnect;
//Hier muss der Begin der abfrage von Daten vom Client rein
handle.Shutdown(SocketShutdown.Both);
handle.Close;
end;