在一个Send事件中写
procedure TForm1.Button1Click(Sender: TObject);
begin
try
WSocket.Addr := '127.0.0.1';
WSocket.Port := '6001';
WSocket.Proto := 'TCP';
WSocket.Connect;
WSocket.SendStr('Test');
finally
wSocket.Close;
end;
end;因为WSocket.Connect还没有链接上,所以WSocket.SendStr('Test')肯定会出错,
那么怎样写才能保证不出错呢?,谢谢!
procedure TForm1.Button1Click(Sender: TObject);
begin
try
WSocket.Addr := '127.0.0.1';
WSocket.Port := '6001';
WSocket.Proto := 'TCP';
WSocket.Connect;
WSocket.SendStr('Test');
finally
wSocket.Close;
end;
end;因为WSocket.Connect还没有链接上,所以WSocket.SendStr('Test')肯定会出错,
那么怎样写才能保证不出错呢?,谢谢!
还要搞个全局变量?_Counter: Integer;//初始化为0
procedure TForm1.Button1Click(Sender: TObject);
begin
Timer.Enable := True;
end;procedure TForm1.TimerTimer(Sender: TObject);
begin
if _Counter >= 5 then
begin
Timer.Enable := False;
Exit;
end else
begin
if WSocket.State <> wsConnected then
begin
try
WSocket.Addr := '127.0.0.1';
WSocket.Port := '6001';
WSocket.Proto := 'TCP';
WSocket.Connect;
finally
wSocket.Close;
end;
end else
begin
WSocket.SendStr('Test');
Timer.Enable := False;
Exit;
end;
end;
_Counter := _Counter + 1;
end;这样我感觉好像绕了一圈一样,呵呵。
var
I: Integer;
begin
try
WSocket.Addr := '127.0.0.1';
WSocket.Port := '6001';
WSocket.Proto := 'TCP';
WSocket.Connect;
I := 1000;
while (I>0) and (WSocket.State <> wsConnected ) do begin
Sleep(15);
Dec(I, 15);
if GetCurrentThreadId = MainThreadId then Application.ProcessMessage;
end;
if (WSocket.State <> wsConnected ) then Exit;
WSocket.SendStr('Test');
finally
wSocket.Close;
end;
end;