回调机制在分布式多层应用中是相当重要的,的确,我们可以能过心跳机制实现同样的原理,但那样会浪费很大的资源;网络的握手、广播、无用数据的传递等;
那么到底是什么是回调机制?其实,并不完全是回调机制,可以由服务器强制对客户应用程序进行某一特定事件的触发;
请主意一点是,如下:
ICallBack_SL = interface;
ICallBack_SLDisp = dispinterface;
ISL = interface;
ISLDisp = dispinterface;/////////接口需要用Dispinterface;
还是让我们来看一看程序,或许会更容易明白些;
这些不是我写的,随便找了一篇
远程数据模块
unit ServerRDM;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
Windows, Messages, SysUtils, Classes, ComServ, ComObj, VCLCom, DataBkr,
DBClient, Server_TLB, StdVcl, Provider, DB, ADODB;
type
TCallBack_SL = class(TRemoteDataModule, ICallBack_SL)
BC_ADOConnection: TADOConnection;
BC_ADOQuery: TADOQuery;
BC_DataSetProvider: TDataSetProvider;
private
{ Private declarations }
protected
class procedure UpdateRegistry(Register: Boolean;
const ClassID, ProgID: string);
override;
procedure FromUser(var UserName: OleVariant);
safecall;
public
Call : OleVariant;/////如何应用回调
{ Public declarations }
end;
implementation
{$R *.DFM}
class procedure TCallBack_SL.UpdateRegistry(Register: Boolean;
const ClassID, ProgID: string);
begin
if Register then
begin
inherited UpdateRegistry(Register, ClassID, ProgID);
EnableSocketTransport(ClassID);
EnableWebTransport(ClassID);
end else
begin
DisableSocketTransport(ClassID);
DisableWebTransport(ClassID);
inherited UpdateRegistry(Register, ClassID, ProgID);
end;
end;
procedure TCallBack_SL.FromUser(var UserName: OleVariant);
begin
Call := UserName;//////////只有给其给值,才可以再下步进行调用;
Call.UserFrom;
end;
initialization
TComponentFactory.Create(ComServer, TCallBack_SL,
Class_CallBack_SL, ciMultiInstance, tmApartment);
end.
客户端程序
unit ClientMianUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,Server_TLB, DB, DBClient, MConnect, SConnect,ActiveX,ComObj,ComServ;
type
TSL = Class(TAutoIntfObject,ISL)////////uses ComObj;
protected
procedure UserFrom;
safecall;
end;
TClientMain = class(TForm)
Label1: TLabel;
Button1: TButton;
SocketConnection1: TSocketConnection;
procedure FormCreate(Sender: TObject);
private
LSSL : TSL;///
{ Private declarations }
public
MyCallBackConnect : TDispatchConnection;
{ Public declarations }
end;
var
ClientMain: TClientMain;
implementation
{$R *.dfm}
procedure TClientMain.FormCreate(Sender: TObject);
var
TypeLib : ITypeLib;
////////uses ACtiveX ,
begin
MyCallBackConnect := SocketConnection1;
MyCallBackConnect.Connected := True;
OleCheck(LoadRegTypeLib(LIBID_Server, 1, 0, 0, TypeLib));//////////相当于注册
LSSL := TSL.Create(TypeLib,ISL);//////实例化;
MyCallBackConnect.AppServer.FromUser(LSSL as IDispatch);//////////这儿执行回调;
end;
{ TSL }
procedure TSL.UserFrom;
begin
ShowMessage('回调机制成功');
end;
end