给个刚开始学clientsocket/serversocket的程序参考下,希望有用。
unit Unit1;
interface
uses
Windows, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, ScktComp, Jpeg, ExtDlgs;
type
TForm1 = class(TForm)
ClientSocket1: TClientSocket;
ServerSocket1: TServerSocket;
Label1: TLabel;
Panel1: TPanel;
Button1: TButton;
Panel2: TPanel;
Image1: TImage;
Image2: TImage;
procedure FormShow(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
procedure ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);
procedure Image1DblClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
PicStrm : TmemoryStream;
ReceiveStrm : TmemoryStream;
LeftSize : Integer;
procedure SendPic;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
Const
SendSize = 8192;
RecSize = 8192;
implementation
{$R *.dfm}
procedure TForm1.SendPic;
var
SendChar : Array[0..SendSize-1] of Char;
begin
if LeftSize > SendSize then
begin
PicStrm.Read(SendChar,SendSize);
ClientSocket1.Socket.SendBuf(SendChar,SendSize);
LeftSize := LeftSize - SendSize;
end
else
begin
PicStrm.Read(SendChar,LeftSize);
ClientSocket1.Socket.SendBuf(SendChar,LeftSize);
end;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
PicStrm := TMemoryStream.Create;
ReceiveStrm := TMemoryStream.Create;
ServerSocket1.Open;
ClientSocket1.Open;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if Image1.Picture.Graphic = Nil then exit;
Button1.Cursor := crHourGlass;
Image1.Picture.Graphic.SaveToStream(PicStrm);
LeftSize := PicStrm.Size;
PicStrm.Position := 0;
SendPic;
end;
procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
RecLen : Integer;
RecChar : Array[0..RecSize-1] of Char;
Jpg : TJpegImage;
Bmp : TBitmap;
begin
RecLen := Socket.ReceiveLength;
Socket.ReceiveBuf(RecChar,RecLen);
ReceiveStrm.Write(RecChar,RecLen);
if RecLen < RecSize then
begin
Try
Image2.Picture.Graphic := nil;
Jpg := TJpegImage.Create;
ReceiveStrm.Position := 0;
Jpg.LoadFromStream(ReceiveStrm);
Image2.Picture.Graphic := Jpg;
except
end;
if Image2.Picture.Graphic = nil then
Try
Bmp := TBitmap.Create;
ReceiveStrm.Position := 0;
Bmp.LoadFromStream(ReceiveStrm);
Image2.Picture.Graphic := Bmp;
Except
end;
ReceiveStrm.Clear;
Socket.SendText('Over');
end
else
Socket.SendText('Wait');
end;
procedure TForm1.ClientSocket1Read(Sender: TObject;
Socket: TCustomWinSocket);
begin
if Socket.ReceiveText = 'Wait' then
SendPic
else
begin
PicStrm.Clear;
Button1.Cursor := crDefault;
end;
end;
procedure TForm1.Image1DblClick(Sender: TObject);
begin
With TOpenPictureDialog.Create(nil) do
try
if Execute then
Image1.Picture.LoadFromFile(FileName);
Finally
Free;
end;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
action := caFree;
end;
end.