我最近也在做关于Socket的程序,仅供参考,欢迎指教
TServerSocket设置成stThreadBlocking
{ TServerThread }
procedure TServerThread.ClientExecute;
var
Stream:TWinSocketStream;
TimeOut:integer;
begin
FreeOnTerminate:=true;
TimeOut:=ConfigRecord.AdvanceIniRecord.IdleTimeOut*1000;//空闲等待时间
while (not Terminated) and ClientSocket.Connected do
begin
try
Stream:=TWinSocketStream.Create(ClientSocket,TimeOut);
try
if Stream.WaitForData(TimeOut) then
begin
//ProcessClientSocket(Stream,Self);
end else
ClientSocket.Close;
finally
Stream.Free;
end;
except
ClientSocket.Close;
end;
end;
end;
procedure TMainFrm.ServerSocketGetThread(Sender: TObject;
ClientSocket: TServerClientWinSocket;
var SocketThread: TServerClientThread);
begin
SocketThread:=TServerThread.Create(false,ClientSocket);
end;
procedure TMainFrm.WMClientThreadBegin(var Msg: TMessage);
begin
inc(ClientSocketCount);
SetStatusBar(ClientSocketCount);
end;
procedure TMainFrm.WMClientThreadEnd(var Msg: TMessage);
begin
dec(ClientSocketCount);
SetStatusBar(ClientSocketCount);
end;
{设置状态栏提示信息}
procedure TMainFrm.SetStatusBar(OnLineUser: integer);
begin
StatusBar1.Panels[1].Text:=Format('在线用户:%d',[OnLineUser]);
end;
{启动服务器}
procedure TMainFrm.RunServerSocket;
begin
with ServerSocket do
begin
Port:=ConfigRecord.AdvanceIniRecord.TcpIpPort;
ThreadCacheSize:=ConfigRecord.AdvanceIniRecord.CacheSize;
Active:=true;
end;
end;
procedure TMainFrm.ServerSocketClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
SendMessage(MainFrm.Handle,WM_ClientThreadEnd,0,0);
end;
procedure TMainFrm.ServerSocketAccept(Sender: TObject;
Socket: TCustomWinSocket);
begin
SendMessage(MainFrm.Handle,WM_ClientThreadBegin,0,0);
end;
procedure TServerThread.ProcessClientSocket(Stream: TWinSocketStream;
ServerClientThread: TServerClientThread);
var
SessionMsg:TSessionRecord;
ReceiveCount:integer;
begin
FillChar(SessionMsg,SizeOf(TSessionRecord),0);
ReceiveCount:=Stream.Read(SessionMsg,SizeOf(TSessionRecord));
if ReceiveCount>0 then
begin
case SessionMsg.SessionMessage of
SM_UserLogin:begin
ProcessUserLogin(Stream,ServerClientThread);
end;
end;
end;
end;