原文出处 《Windows网络编程技术》第8章 完成端口模型
由于原书附的是C代码,我把其翻译成Delphi代码。
其中winsock2.pas在delphi中不带,要另外下载http://jungla.dit.upm.es/~bti/files/winsock2.pas
program CompletionIO;
{$APPTYPE CONSOLE}
uses
SysUtils,
WinSock2 in 'WinSock2.pas',
Mains in 'Mains.pas';
begin
main();
end.
// Module Name: iocmplt.cpp
//
// Description:
//
// This sample illustrates how to develop a simple echo server Winsock
// application using the completeion port I/O model. This
// sample is implemented as a console-style application and simply prints
// messages when connections are established and removed from the server.
// The application listens for TCP connections on port 5150 and accepts them
// as they arrive. When this application receives data from a client, it
// simply echos (this is why we call it an echo server) the data back in
// it's original form until the client closes the connection.
//
// 2005-2-5
// cpp convert to delphi pas by johnson
//
unit Mains;
interface
uses Windows, WinSock2, WinSock, Sysutils;
const
PORT = 5150;
DATA_BUFSIZE = 8192;
type
LPVOID = Pointer;
LPPER_IO_OPERATION_DATA = ^ PER_IO_OPERATION_DATA ;
PER_IO_OPERATION_DATA = packed record
Overlapped: OVERLAPPED;
DataBuf: TWSABUF;
Buffer: array [0..DATA_BUFSIZE] of CHAR;
BytesSEND: DWORD;
BytesRECV: DWORD;
end;
LPPER_HANDLE_DATA = ^ PER_HANDLE_DATA;
PER_HANDLE_DATA = packed record
Socket: TSocket;
end;
procedure main;
implementation
function ServerWorkerThread(CompletionPortID: LPVOID): DWORD; stdcall; forward;
procedure printf(Fmt: string; num: Integer);
begin
WriteLn(Format(Fmt, [num]));
end;
procedure main;
var
InternetAddr: SOCKADDR_IN;
Listen: TSOCKET;
Ac