{$MODE OBJFPC}
uses
cthreads, Classes, blcksock, sockets, Synautil, SysUtils, nettools;
var
soket : TUDPBlockSocket;
clientNumer : string;
buf : TcharArray;
s : string;
bytesReceived : longint;
remoteIP, remotePort : string;
Type
TreadThread = class(TThread)
protected
procedure Execute; override;
public
soket : TUDPBlockSocket;
Constructor Create(CreateSuspended : boolean);
end;
TwriteThread = class(TThread)
protected
procedure Execute; override;
public
soket : TUDPBlockSocket;
Constructor Create(CreateSuspended : boolean);
end;
constructor TreadThread.Create(CreateSuspended : boolean);
begin
inherited Create(CreateSuspended);
FreeOnTerminate := True;
end;
procedure TreadThread.Execute;
var buf : TcharArray;
begin
while (not Terminated) do begin
bytesReceived:= soket.recvBuffer(PChar(@buf), sizeof(TcharArray));
checkError(soket);
writeln(buf);
sleep(100);
end;
end;
constructor TwriteThread.Create(CreateSuspended : boolean);
begin
inherited Create(CreateSuspended);
FreeOnTerminate := True;
end;
procedure TwriteThread.Execute;
var buf : TcharArray;
s : String;
begin
while (not Terminated) do begin
s:= '->' + clientNumer;
buf:= s;
soket.SendBuffer(PChar(@buf[0]), length(s));
checkError(soket, 'write');
sleep(100);
end;
end;
var
readThread : TreadThread;
writeThread : TwriteThread;
begin
soket:= TUDPBlockSocket.Create;
soket.bind('0.0.0.0', '9090');
soket.SetRemoteSin(remoteServerIP, '1500');
checkError(soket);
clientNumer:= '1';
if paramcount = 1 then clientNumer:= paramstr(1);
buf[0]:= char(strtoint(clientNumer));
soket.SendBuffer(PChar(@buf[0]), 1);
sleep(10);
soket.Free;
soket := TUDPBlockSocket.Create;
soket.CreateSocket;
soket.bind('0.0.0.0', '9090');
checkError(soket);
while True do begin
bytesReceived:= soket.recvBuffer(PChar(@buf), sizeof(buf));
if buf[0] = #3 then begin
writeln('Handshake!');
break;
end;
end;
soket.CloseSocket;
soket.Free;
s:=transcriptBuf2String(buf, 2, bytesReceived - 1);
s:=copy(s, pos('@', s) + 1, length(s));
remoteIP:=copy(s, 0, pos(':', s) - 1);
remotePort:=copy(s, pos(':', s) + 1, length(s));
writeln('other clinet is @', remoteIP, ':', remotePort, '!');
//
// At this point I have correct IP and Port of the other Client!!!!!!!
//
//
//
// now I'm trying to connect and read/write... nothing happens :( why?
//
Soket:= TUDPBlockSocket.Create;
Soket.CreateSocket;
Soket.bind('0.0.0.0', '9090'); checkError(Soket, 'bind');
Soket.Connect(remoteIP, remotePort); checkError(Soket, 'connect');
readThread:=TreadThread.Create(false);
readThread.soket:=soket;
readThread.Start;
writeThread:= TwriteThread.Create(false);
writeThread.soket:=soket;
writeThread.Start;
readln;
Soket.CloseSocket;
Soket.Free;
end.