用 API 做的 ServerSocket 例子 (轉)

worldblog發表於2007-12-12
用 API 做的 ServerSocket 例子 (轉)[@more@]

program Server;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Winsock,
  ;

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)+' Dinnect');
end;

//主
var
  MyWSA: WSAData;
  Svr,Clt: TSockAddr;
  NameLen:Integer;
  hSocket,s: TSocket;
  TimeOut:integer;
  ThreadCount:integer;
  hThread:Thandle;
  ThreadID:D;
  Param:^TParam; 
begin
  If Wtartup(MAKEWORD(2,2), MyWSA) <> 0 Then  //初始化
  Begin
  WSACleanup;
  Writeln('WSAStartup() Fail');
  Exit;
  end;
  hSocket := Socket(AF_, 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 :=_addr(PChar('127.0.0.1'));//server的為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.

//原始碼


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-992164/,如需轉載,請註明出處,否則將追究法律責任。

相關文章