{ Private declarations }
Reciving: boolean;
DataSize: integer;
Data: TMemoryStream;
procedure TForm1.FormCreate(Sender: TObject);
begin
// Open the SENDING socket.
ServerSocket1.Active:= true;
end;
procedure TForm1.ClientSocket1Connect(Sender: TObject;
Socket: TCustomWinSocket);
begin
// Send command to start the file sending.
Socket.SendText('send');
end;
procedure TForm1.ClientSocket1Read(Sender: TObject;
Socket: TCustomWinSocket);
var
s, sl: string;
begin
s:= Socket.ReceiveText;
// If we're not in recieve mode:
if not Reciving then
begin
// Now we need to get the length of the data stream.
SetLength(sl, StrLen(PChar(s))+1); // +1 for the null terminator
StrLCopy(@sl[1], PChar(s), Length(sl)-1);
DataSize:= StrToInt(sl);
Data:= TMemoryStream.Create;
// Delete the size information from the data.
Delete(s, 1, Length(sl));
Reciving:= true;
end;
// Store the data to the file, until we've received all the data.
try
Data.Write(s[1], length(s));
if Data.Size = DataSize then
begin
Data.Position:= 0;
Image2.Picture.Bitmap.LoadFromStream(Data);
Data.Free;
Reciving:= false;
Socket.Close;
end;
except
Data.Free;
end;
end;
procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
ms: TMemoryStream;
begin
// The client wants us to send the file.
if Socket.ReceiveText = 'send' then
begin
ms:= TMemoryStream.Create;
try
// Get the data to send.
Image1.Picture.Bitmap.SaveToStream(ms);
ms.Position:= 0;
// Add the length of the data, so the client
// will know how much data to expect.
// Append #0 so it can determine where the size info stops.
Socket.SendText(IntToStr(ms.Size) + #0);
// Send it (the socket owns the stream from now on).
Socket.SendStream(ms);
except
// So only free the stream if something goes wrong.
ms.Free;
end;
end;
end;
Aufruf :
procedure TForm1.Button1Click(Sender: TObject);
begin
ClientSocket1.Active:= true;
end;
Keine Kommentare:
Kommentar veröffentlichen