给个例子吧,如下:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ScktComp;
type
TForm1 = class(TForm)
ServerSocket1: TServerSocket;
procedure ServerSocket1Accept(Sender: TObject;
Socket: TCustomWinSocket);
procedure ServerSocket1ClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure ServerSocket1ClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure ServerSocket1ClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
procedure ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.ServerSocket1Accept(Sender: TObject;
Socket: TCustomWinSocket);
begin
if not AllowConnect(Socket.RemoteAddress) then //验证远程主机的IP是否允许它连接
Socket.Close; //函数AllowConnect请自定义,如果
//没有限制连接,这个事件句柄就不用写了
end;
procedure TForm1.ServerSocket1ClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
LogMessage('有IP地址为'+Socket.RemoteAddress+'的主机已经连接');
end;
procedure TForm1.ServerSocket1ClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
LogMessage('有IP地址为'+Socket.RemoteAddress+'的主机断开了它的连接');
end;
procedure TForm1.ServerSocket1ClientError(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
LogMessage('与IP地址为'+Socket.RemoteAddress+'的主机连接发生错误!');
Socket.Close;
ErrorCode :=0; //如果你不想程序抛出异常,请把ErrorCode置为0
end;
procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var ms: TMemoryStream;
len: Integer;
begin
len := Socket.ReceiveLength
LogMessage('接收到IP地址为'+Socket.RemoteAddress+
'的主机发送的数据,长度为='+
IntToStr(len)+'字节');
ms := TMemoryStream.Create;
try
ms.SetSize(len);
Socket.ReceiveBuf(ms.Memory,len);
//这时,已经把本次事件在网络上所收到的数据存到流中了。
//下面,想怎么用就怎么用。
finally
ms.Free;
end;
end;
end.