program Server;
{$APPTYPE CONSOLE}
uses
SysUtils,
Winsock,
Windows;
type
TParam=record
TrdId:integer;
Sckt:TSocket;
end;
//子线程函数
function ChildThrd(p:Pointer):LongInt;stdcall;
var
PkLen:integer;
ThreadId:integer;
ASocket:TSocket;
buf:array[0..63] of char;
begin
Result:=0;
ThreadId:=TParam(p^).TrdId;
ASocket:=TParam(p^).Sckt;
Writeln('Thread '+IntToStr(ThreadId)+' Create');
PkLen:=1;
while PkLen>0 do
begin
FillChar(buf,SizeOf(buf),0);
PkLen:=Recv(ASocket,buf,SizeOf(buf),0); //接收数据
Write(buf);
if PkLen>0 then
begin
Send(ASocket,buf,PkLen,0);//发送数据
end;
end;
CloseSocket(ASocket); //关闭socket
Dispose(p);
Writeln('Thread '+IntToStr(ThreadId)+' End');
Writeln('Socket '+IntToStr(ASocket)+' DisConnect');
end;
//主程序
var
MyWSA: WSAData;
Svr,Clt: TSockAddr;
NameLen:Integer;
hSocket,s: TSocket;
TimeOut:integer;
ThreadCount:integer;
hThread:Thandle;
ThreadID:DWord;
Param:^TParam;
begin
If WSAStartup(MAKEWORD(2,2), MyWSA) <> 0 Then //初始化
Begin
WSACleanup;
Writeln('WSAStartup() Fail');
Exit;
end;
hSocket := Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //创建socket
If hSocket = INVALID_SOCKET Then
Begin
WSACleanup;
Writeln('Socket() Fail');
Exit;
End;
Svr.sin_family := AF_INET;
Svr.sin_port := htons(176); //server端口号为176
Svr.sin_addr.S_addr := inet_addr(PChar('127.0.0.1'));//server的ip地址为127.0.0.1
If Bind(hSocket, Svr, SizeOf(Svr)) = SOCKET_ERROR Then //绑定socket
Begin
CloseSocket(hSocket);
WSACleanup;
Writeln('Bind() Fail');
Exit;
end;
if Listen(hSocket,256) = SOCKET_ERROR Then //socket开始侦听,最大同时连接数为256个
begin
CloseSocket(hSocket);
WSACleanup;
Writeln('Listen() Fail');
Exit;
end;
TimeOut:=3000;
ThreadCount:=0;
Writeln('Listening......');
while true do
begin
NameLen:=SizeOf(Clt);
s:=Accept(hSocket,@Clt,@NameLen);//接受一个连接
if s = SOCKET_ERROR Then
begin
CloseSocket(hSocket);
WSACleanup;
Writeln('Accept() Fail');
Exit;
end
else
begin
Writeln('Socket '+IntToStr(s)+' Connect');
if SetSockOpt(s,SOL_SOCKET,SO_RCVTIMEO,PChar(@TimeOut),SizeOf(TimeOut))=SOCKET_ERROR then //设置接收超时为3秒
begin
CloseSocket(s);
CloseSocket(hSocket);
WSACleanup;
Writeln('SetSockOpt() Fail');
Exit;
end;
if SetSockOpt(s,SOL_SOCKET,SO_SNDTIMEO,PChar(@TimeOut),SizeOf(TimeOut))=SOCKET_ERROR then //设置发送超时为3秒
begin
CloseSocket(s);
CloseSocket(hSocket);
WSACleanup;
Writeln('SetSockOpt() Fail');
Exit;
end;
new(Param);
Param^.TrdId:=ThreadCount;
Param^.Sckt:=s;
hThread:=CreateThread(nil,0,@ChildThrd,Param,0,ThreadID); //创建childthrd子线程
if hThread=0 then
begin
Writeln('CreateThread() Fail');
end
else
begin
Inc(ThreadCount);
end;
end;
end;
CloseSocket(hSocket); //关闭socket
WSACleanup;
end.
//源码下载 http://ono.3322.org/mysoft/serversocket.zip