不好意思,说实话,上面各位的代码没有一个可以应付得了
在 SocketConnection1.Connected:=true; 时,应用服务器没有开机,客户机长时间等待的问题。
因为在单线程程序中等待一个未开机的应用服务器,只要执行到上一句,主线程就停止响应,
直到SocketConnection的Connected为True或抛出一个异常,大约时间在60秒,因为WinSocket被初始化的超时时间为60秒左右。
用多线程或事件驱动可以解决这个问题。
以下代码完全基于事件驱动机制,定时时间任选。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ScktComp, StdCtrls, Db, DBClient, MConnect, SConnect, ExtCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
ClientSocket1: TClientSocket;
SocketConnection1: TSocketConnection;
Timer1: TTimer;
procedure FormCreate(Sender: TObject);
procedure ClientSocket1Connect(Sender: TObject;
Socket: TCustomWinSocket);
procedure Button1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure SocketConnection1AfterConnect(Sender: TObject);
procedure ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
ClientSocket1.Address := SocketConnection1.Address; //应用服务器IP
ClientSocket1.Port := SocketConnection1.Port; //应用服务器 Socket Server 端口
Timer1.Enabled := False;
Timer1.Interval := 5000; //定时5秒
end;
procedure TForm1.ClientSocket1Connect(Sender: TObject;
Socket: TCustomWinSocket);
begin
SocketConnection1.Connected := True; //因为ClientSocket使用了跟SocketConnection一样的地址和端口
//若它连接成功的话,对方肯定开了而且开了 Socket Server程序
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ClientSocket1.Active := True; //异步Socket不会阻塞主线程的运行
Timer1.Enabled := True;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
(Sender as TTimer).Enabled := False; //定时时间到,关闭Socket
ClientSocket1.Active := False;
if not SocketConnection1.Connected then
ShowMessage('连接失败超时,时间:'+
IntToStr(Timer1.Interval div 1000)+'秒');
end;
procedure TForm1.SocketConnection1AfterConnect(Sender: TObject);
begin
ShowMessage('成功连接到AppServer');
end;
procedure TForm1.ClientSocket1Error(Sender: TObject;
Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
var msg: String;
begin
case ErrorCode of
10061: msg := '对方没开Socket Server';
10054: msg := '对方没开机'; //Timer1的定时时间大于60秒时才起作用
else msg := '连接失败!';
end;
ErrorCode := 0;
Timer1.Enabled := False;
ShowMessage(msg);
end;
end.