各位前辈能否给个serversocket.ThreadEnd应用的示例源代码?一小段能说明问题就行(50分)

  • 主题发起人 主题发起人 mfcliu
  • 开始时间 开始时间
M

mfcliu

Unregistered / Unconfirmed
GUEST, unregistred user!
各位前辈能否给个serversocket.ThreadEnd应用的示例源代码?一小段能说明问题就行
 
当ServerSocket的ServerType为stThreadBlocking时才会激发ThreadStart和ThreadEnd事件,考虑到ServerSocket会使用到线程池,当ClientSocket断开连接时并不会激发ThreadEnd事件,可用ServerSocket.Active:=True测试。
 
我已经将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.




 
为什么一定要在OnThreadStart和OnThreadEnd里操作呢?
在OnClientConnect和OnClientDisconnect里不是更好吗?
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
D
回复
0
查看
905
DelphiTeacher的专栏
D
后退
顶部