procedure TForm1.TCPServerExecute(AContext: TIdContext);
var
FSTream: TFileStream;
df:
String;
tmpClientData : TClientData;
begin
if not assigned(AContext.Data)
then
begin
AContext.Connection.Disconnect;
exit;
end;
// read clientdata
try
tmpClientData := TClientData(AContext.Data);
except
AContext.Connection.Disconnect;
exit;
end;
// check state
if (tmpClientData.Status = cCSGoing2Disconnect)
or
(tmpClientData.Status = cCSDisconnected)
then
begin
AContext.Connection.Disconnect;
exit;
end;
// get command
try
tmpClientData.LastCmd := AContext.Connection.Socket.ReadLn(#$A,5000,1024);
except
tmpClientData.LastCmd := '
';
end;
// check the old command
case tmpClientData.LastIntCmd
of
// GUY WANTS TO SEND FILE
1:
begin
savefilepath := DestinationEdit.Text + AContext.Connection.IOHandler.ReadLn;
Log(AContext.Binding.PeerIP+'
wants to send file: "'+ExtractName(savefilepath)+'
"');
ButtonCaption('
receive');
EButton4.Enabled := True;
end;
// UPLOAD FILE
2:
begin
Log('
upload file...');
TCPSendCmd(4);
try
// upload
FStream := TFileStream.Create(uploadfilepath, fmOpenRead
or fmShareDenyWrite);
TCPClient.IOHandler.
Write(FStream,0,true);
// disconnect
AContext.Connection.Disconnect;
if TCPClient.Connected
then
TCPClient.Disconnect;
tmpClientData.Status := cCSDisconnected;
finally
FStream.Free;
end;
Log('
successfully uploaded');
ButtonCaption('
upload');
EButton4.Enabled := False;
EButton2.Enabled := True;
EButton5.Enabled := True;
end;
// GUY REFUSED FILE
3:
begin
Log('
guy refused to download file');
// disconnect
AContext.Connection.Disconnect;
if TCPClient.Connected
then
TCPClient.Disconnect;
tmpClientData.Status := cCSDisconnected;
ButtonCaption('
upload');
EButton4.Enabled := False;
EButton2.Enabled := True;
EButton5.Enabled := True;
end;
// DOWNLOAD FILE
4:
begin
try
if FileExists(savefilepath)
then
begin
Log('
file was already existing');
df := savefilepath;
DeleteFile(
df);
Log('
old file deleted!');
end
else if DirectoryExists(ExtractFilePath(savefilepath)) = false
then
begin
CreateDir(ExtractFilePath(savefilepath));
Log('
directory "'+ExtractFilePath(savefilepath)+'
" created');
end;
Log('
download...');
try
// download
FStream := TFileStream.Create(savefilepath, fmCreate);
AContext.connection.IOHandler.ReadStream(fstream);
// disconnect
AContext.Connection.Disconnect;
if TCPClient.Connected
then
TCPClient.Disconnect;
tmpClientData.Status := cCSDisconnected;
finally
FStream.Free;
end;
Log('
file successfully downloaded!');
ButtonCaption('
upload');
EButton4.Enabled := False;
EButton2.Enabled := True;
EButton5.Enabled := True;
except
on e:
Exception do
Log(e.
Message);
end;
end;
// RECEIVE CHAT MESSAGE
5:
begin
Log(AContext.Binding.PeerIP+'
: '+AContext.Connection.IOHandler.ReadLn);
AContext.Connection.Disconnect;
end;
end;
end;