delphi的帮助中有Writing client threads 和 Writing server threads代码示例。
procedure TMyClientThread.Execute;
var
TheStream: TWinSocketStream;
buffer: string;
begin
{ create a TWinSocketStream for reading and writing }
TheStream := TWinSocketStream.Create(ClientSocket1.Socket, 60000);
try
{ fetch and process commands until the connection or thread is terminated }
while (not Terminated) and (ClientSocket1.Active) do
begin
try
GetNextRequest(buffer); { GetNextRequest must be a thread-safe method }
{ write the request to the server }
TheStream.Write(buffer, Length(buffer) + 1);
{ continue the communication (e.g. read a response from the server) }
...
except
if not(ExceptObject is EAbort) then
Synchronize(HandleThreadException); { you must write HandleThreadException }
end;
end;
finally
TheStream.free;
end;
end;
procedure TMyServerThread.ClientExecute;
var
Stream : TWinSocketStream;
Buffer : array[0 .. 9] of Char;
begin
{ make sure connection is active }
while (not Terminated) and ClientSocket.Connected do
begin
try
Stream := TWinSocketStream.Create(ClientSocket, 60000);
try
FillChar(Buffer, 10, 0); { initialize the buffer }
{ give the client 60 seconds to start writing }
if Stream.WaitForData(60000) then
begin
if Stream.Read(Buffer, 10) = 0 then { if can't read in 60 seconds }
ClientSocket.Close; { close the connection }
{ now process the request }
...
end
else
ClientSocket.Close; { if client doesn't start, close }
finally
Stream.Free;
end;
except
HandleException;
end;
end;
end;