首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

indy做聊天系统,用线程时时取得服务器信息的有关问题~

2013-01-07 
indy做聊天系统,用线程时时取得服务器信息的问题~~他说这个程序能不断的接收服务器传来的消息,可他就在cli

indy做聊天系统,用线程时时取得服务器信息的问题~~
他说这个程序能不断的接收服务器传来的消息,可他就在client组件connected事件里创建了一下线程,运行完自动就关闭了,如何能一直接收消息呢?



这个是接收消息的线程

procedure TMainThread.Foo;
var
Msg:string;
bool: boolean;
begin
bool:=true;
while bool do begin
    try
    Msg:= Form6.IdTCPClient1.IOHandler.ReadLn;
     if(Msg='') then
     bool:=false
     else
     begin
     M_Lock.Enter;
     M_MsgList.Add(Msg);
     M_Lock.Leave;
     end;
    except
    bool:=false;
    end;
end;
end;

Procedure TMainThread.Execute;//线程启动
begin
FreeOnTerminate:=True;
Foo;
End;
End.


然后他就只在client组件connected事件时创建了线程
procedure TForm6.ConetClick(Sender: TObject);
begin
try
   if not (IdTCPClient1.Connected) then
   begin
    IdTCPClient1.Connect;
    TMainThread.Create(false);
    IdTCPClient1.IOHandler.writeln('lianjie');
    ShowMessage('连接成功');
   end;
    except
    ShowMessage('连接失败');
end;
end;


然后用timer把线程取得的消息放入memo

procedure TForm6.Timer1Timer(Sender: TObject);
var
Msg:String;
begin
M_Lock.Enter;
while M_MsgList.Count > 0 do
   begin
   Msg:='';
   Msg := M_MsgList[0];
   M_MsgList.Delete(0);
   if(Msg<>'')then
   Memo1.Lines.Add(Msg);
end;
M_Lock.Leave;
end;

[解决办法]
引用:
我按那个教程,就在client组件connected事件里创建这个线程,确实能随时接收到服务器消息,请问这是为什么啊?这个线程不是运行一次就没了么?

while bool do begin
    try
    Msg:= Form6.IdTCPClient1.IOHandler.ReadLn;
     if(Msg='') then
     bool:=false
     else
     begin
     M_Lock.Enter;
     M_MsgList.Add(Msg);
     M_Lock.Leave;
     end;
    except
    bool:=false;
    end;
end;
问题在
while bool do 这里
bool=false 才会结束
你看什么情况下才 bool=false? 
所以他就一直不会结束得

热点排行