⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 unitsocketthread.pas

📁 1
💻 PAS
字号:
unit UnitSocketThread;

interface

uses
  Classes,windows,WinSock,SysUtils;

type
  SocketThread = class(TThread)
  private
    { Private declarations }
  protected
    procedure Execute; override;
  public
    Port:word;
  end;

implementation
uses
UnitMain,UnitAcceptThread;
{ Important: Methods and properties of objects in visual components can only be
  used in a method called using Synchronize, for example,

      Synchronize(UpdateCaption);

  and UpdateCaption could look like,

    procedure SocketThread.UpdateCaption;
    begin
      Form1.Caption := 'Updated in a thread';
    end; }

{ SocketThread }

procedure SocketThread.Execute;
var
asock,sock:TSocket;
addr,cliaddr:TSockAddr;
err,i,len:integer;
wsd:WSADATA;
fd_read:TFDSet;
timeout:TTimeVal;
athread:AcceptThread;
begin
WSAStartup(MAKEWORD(2,2),wsd);
sock:=Socket(AF_INET,SOCK_STREAM,WinSock.IPPROTO_TCP);
addr.sin_family:=AF_INET;
addr.sin_port:=htons(Port);
addr.sin_addr.S_addr:=htonl(INADDR_ANY);
err:=bind(sock,addr,sizeof(TSockAddrIn));
if err<>0 then MessageBox(MainForm.Handle,pAnsiChar('端口帮定错误,请在参数设置中修改端口,并且重新启动程序:'+IntToStr(err)),'错误',MB_OK);
err:=listen(sock,5);
while not Terminated do
   begin
   FD_ZERO(fd_read);
   FD_SET(sock,fd_read);
   timeout.tv_sec:=0;
   timeout.tv_usec:=500;
   if select(0,@fd_read,nil,nil,@timeout)>0 then//检查队列中等待的连接,大于1则继续
      begin
      if FD_ISSET(sock,fd_read) then
         begin
         for i:=0 to fd_read.fd_count-1 do
            begin
            len:=sizeof(addr);
            asock:=accept(sock,@addr,@len);
            if ASock <> INVALID_SOCKET then
               begin
               athread:=AcceptThread.Create(true);
               athread.FreeOnTerminate:=true;
               athread.Priority:=tpLower;
               athread.SetPar(asock,addr);
               athread.Resume;
               end
            else
               begin
               MessageBox(MainForm.Handle,'接收错误','asd',MB_OK);
               end;
            end;
         end;
      end;
   end;
CloseSocket(sock);
  { Place thread code here }
end;

end.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -