Client:
// 连接按扭
procedure TFrmUpdateClient.BtnConnectClick(Sender: TObject);
begin
IdTCPClientUpdate.Host := txtIP; // 服务端IP
IdTCPClientUpdate.Port := txtPort; //服务端端口
ProgressBar1.Position := 0;
bConnect:=TRUE;
try
if IdTCPClientUpdate.Connected then IdTCPClientUpdate.Disconnect ;
IdTCPClientUpdate.Connect(5000); //连接
except
ShowMessage('连接服务器失败!');
end;
end;
// 客户端发送按钮
procedure TFrmUpdateClient.btnSendClick(Sender: TObject);
var
cmd : string; // 接收到服务端的字符串信息
begin
while bConnect do
begin
cmd := UpperCase(IdTCPClientUpdate.ReadLn); //服务端发送的命令字符串
if cmd = 'BEGIN' then //开始传输
begin
try
IdTCPClientUpdate.WriteLn(Format('%d|%d|%s', [AFileStream.Size, FileCheckSum, ExtractFileName(txtFileName.Text)]));
except
ShowMessage('发送命令失败');
Exit;
end;
Continue;
end;
if cmd = 'END' then
begin //传输完成
Exit;
end;
IdTCPClientUpdate.CloseWriteBuffer; //结束发送缓冲
end;
end;
服务器端:
//启动服务器按钮
procedure TFrmUpdateSever.BtnUpdateStartClick(Sender: TObject);
begin
Try
IdTCPServerUpdate.DefaultPort := StrToIntDef(txtPort.Text, 9925);
if not IdTCPServerUpdate.Active then IdTCPServerUpdate.Active := True;
Except
ShowMessage('服务器启动失败!');
Exit;
end;
end;
// 关闭服务
procedure TFrmUpdateSever.BtnUpateCLoseClick(Sender: TObject);
begin
try
if IdTCPServerUpdate.Active then IdTCPServerUpdate.Active := FALSE;
except
ShowMessage('关闭服务器失败!');
end;
end;
//添加IdTCPServer的OnExecute事件
procedure TFrmUpdateSever.IdTCPServerUpdateExecute(AThread: TIdPeerThread);
var
cmd : string;
begin
with AThread.Connection do //已经连街上的一个进程
begin
FilePath:=EditFilePath.Text;//ExtractFilePath(Application.ExeName);
try
WriteLn('BEGIN'); //提示客户端开始接收
cmd := ReadLn;
WriteLn('END'); //提示服务器传输完成
except
ShowMessage( '连接服务器失败或者对方已经中断传输!');
end;
Disconnect;
end;
end;