Twsockt为什么连接和发送写在同一个click事件里就会出错
Twsockt为什么连接和发送写在同一个click事件里就会出错
procedure TForm1.Button2Click(Sender: TObject);
begin
WSocket1:= TWsocket.Create(nil);
WSocket1.Proto :='tcp';
WSocket1.Addr :='192.168.2.103';
WSocket1.Port :='3399';
WSocket1.LineMode :=false;
WSocket1.Connect;
sleep(10000) ;
WSocket1.sendstr ('34243432');
end;
为什么连接和发送写在同一个click事件里就会出错,我加个等待连接的时间也不行,而把发送写在另一个click事件里就可以成功发送数据
procedure TForm2.Button1Click(Sender: TObject); var n: DWORD; begin WSocket1:= TWsocket.Create(nil); WSocket1.Proto :='tcp'; WSocket1.Addr :='192.168.2.103'; WSocket1.Port :='3399'; WSocket1.LineMode :=false; WSocket1.Connect; n := GetTickCount; while (WSocket1.State <> wsConnected) and ((GetTickCount - n) <= 10000) do//等待10秒,直到WSocket1的状态为连接成功状态 begin Sleep(100); Application.ProcessMessages; end; if WSocket1.State = wsConnected then WSocket1.sendstr ('34243432'); end;
因为WSocket是利用消息机制处理数据传输,你用Sleep会阻塞WSocket的数据传输。