1.打开连接.
IdTCPClient1.port:=6666;
IdTCPClient1.host:='127.0.0.1';
IdTCPClient1.Connect;
IdTCPClient1.IOHandler.WriteLn('我是中国人China',IndyTextEncoding(TEncoding.ANSI));
//以上可以解决中文乱码的问题
// IdTCPClient1.IOHandler.WriteLn(UTF8Encode('我是中国人China'));
doRead:=true;
CreateThread(nil,0,@ReadThread,nil,0,td);
2.线程函数
var
td:Dword;
doread:boolean;
{$R *.dfm}
procedure ReadThread;
var
s:String;
idbuf:TIdBytes;
begin
form3.mmo1.Lines.Add('Begin reading…');
//s:=form3.IdTCPClient1.IOHandler.ReadLn;这部分一定要有回车符才行.
while doread do
begin
form3.IdTCPClient1.IOHandler.CheckForDataOnSource();
if form3.IdTCPClient1.IOHandler.InputBuffer.Size >0 then begin
SetLength(idbuf, form3.IdTCPClient1.IOHandler.InputBuffer.Size);
form3.IdTCPClient1.IOHandler.ReadBytes( idbuf, form3.IdTCPClient1.IOHandler.InputBuffer.Size,false);
s := tencoding.Default.GetString(idbuf);
form3.mmo1.Lines.Add(s);
sleep(100);
end;
end;
end;
3.关闭
doread:=false;
IdTCPClient1.Disconnect;