我已经将serversocket设置为ThreadBlocking,ServerSocketThreadStart可以激发,TServerSocket.OnThreadEnd在连接断开的时候不能被调用,但是在程序被关闭的时候会被调用。请看如下代码:
//in unit1
procedure TForm1.ServerSocketGetThread(Sender: TObject;
ClientSocket: TServerClientWinSocket;
var SocketThread: TServerClientThread);
begin
SocketThread:=TMyServerThread.Create(ChatMemo,LstConn,False,ClientSocket);
end;
procedure TForm1.ServerSocketThreadEnd(Sender: TObject;
Thread: TServerClientThread);
begin
LstTh.Items.Delete(LstTh.Items.IndexOf('Thread
<'+inttostr(Thread.ThreadID)+'>'));
EdtThActive.Text:=inttostr(Thread.ServerSocket.ActiveThreads);
EdtThIdle.Text:=inttostr(Thread.ServerSocket.IdleThreads);
EdtThCache.Text:=inttostr(Thread.ServerSocket.ThreadCacheSize);
end;
//in unit2
type
TMyServerThread = class(TServerClientThread)
Private
FMemo:TMemo;
FListBox:TListBox;
Buffer:Array[0..1025] of char;
Protected
Procedure ClientExecute;override;
Procedure DoDisplayCreate();
Procedure DoDisplayBuffer();
Public
Constructor Create(Memo:TMemo;ListBox:TListBox;CreateSuspended:Boolean;
ASocket:TServerClientWinSocket);
end;
implementation
Constructor
TMyServerThread.Create(Memo:TMemo;ListBox:TListBox;CreateSuspended:Boolean;
ASocket:TServerClientWinSocket);
begin
Inherited Create(CreateSuspended,ASocket);
FMemo:=Memo;
FListBox:=ListBox;
end;
Procedure TMyServerThread.DoDisplayCreate();
begin
//
end;
Procedure TMyServerThread.DoDisplayBuffer();
var
conn:integer;
begin
FMemo.Lines.Add('Thread<'+inttostr(ThreadId)+'>
Client<'+ClientSocket.RemoteHost+
'> Port<'+inttostr(ClientSocket.RemotePort)+'> : '+Buffer);
For conn:=0 to ClientSocket.ServerWinSocket.ActiveConnections-1 do
begin
ClientSocket.ServerWinSocket.Connections[conn].SendText(Buffer);
end;
end;
Procedure TMyServerThread.ClientExecute();
Var
Stream:TWinSocketStream;
begin
while (not Terminated) and ClientSocket.Connected do
begin
try
Stream:=TWinSocketStream.Create(ClientSocket,5000);
try
FillChar(Buffer,1025,0);
if Stream.WaitForData(60000) then
begin
if Stream.Read(Buffer,1025)=0 then
begin
ClientSocket.Close();
end
else
begin
SynChronize(DoDisplayBuffer);
end;
end;
finally
Stream.Free;
end;
except
HandleException;
end;
end;
end;
end.