unit DownTread;
interface
uses
Classes, Windows, Messages, SysUtils, Graphics, Controls, Forms, Dialogs, winsock;
type
TDownTread = class(TThread)
private
FSocket: TSocket;
FSockAddr: TSockAddr;
FSockAddrIn : TSockAddrIn; //利用消息实时获知UDP消息
procedure updatalabel;
procedure updatalabe2;
procedure updatalabe3;
published
constructor Create(StartPos:integer;FileName:string;SaveName:string;
PathType:integer);
destructor Destroy; override;
protected
procedure Execute; override;
// 1---为绝对路径
end;
implementation
uses main;
constructor TDownTread.Create(StartPos:integer;FileName:string;SaveName:string;
PathType:integer);
var
TempWSAData: TWSAData;
begin
inherited Create(true);
///////////////////////////////////////////////////////////////////////
// 初始化SOCKET
///////////////////////////////////////////////////////////////////////
if WSAStartup($101, TempWSAData)=1 then
showmessage('StartUp Error!');
FSocket := Socket(AF_INET, SOCK_STREAM, 0);
if (FSocket = INVALID_SOCKET) then //Socket创建失败
begin
showmessage(inttostr(WSAGetLastError())+' Socket创建失败');
CloseSocket(FSocket);
end;
//本机SockAddr绑定
FSockAddr.sin_family := AF_INET;
FSockAddr.sin_addr.S_addr := inet_addr('127.0.0.1'); //INADDR_ANY;
FSockAddr.sin_port := htons(25344);
if connect(FSocket, FSockAddr, sizeof(FSockAddr)) <> 0 then
begin
showmessage('connect fail');
end;
//以上为建立客户socket
////////////////////////////////////////////////////////////////
Synchronize(updatalabel);
FreeOnTerminate := true; // Thread Free Itself when terminated
Suspended := false; // Continue the thread
end;
procedure TDownTread.Execute;
var
SendBuf : string;
GetBuf : array [0..1024] of char;
begin
Synchronize(updatalabe3);
while true do
begin
SendBuf := '1111';
Send(FSocket, SendBuf, length(sendbuf), 0);
//recv如何利用超时退出的功能?????????????
recv(FSocket,GetBuf, 1024, 0); //阻塞接收,如何超时退出
sleep(1000);
Synchronize(updatalabe3);
end
end;
destructor TDownTread.Destroy;
begin
Synchronize(updatalabe2);
inherited destroy;
end;
procedure TDownTread.updatalabel;
begin
MainForm.label1.tag:=MainForm.label1.tag+1;
MainForm.label1.caption:='ThreadID'+IntToStr(ThreadID)+' '+inttostr(MainForm.label1.tag);
end;
procedure TDownTread.updatalabe2;
begin
MainForm.label2.tag:=MainForm.label2.tag+1;
MainForm.label2.caption:='ThreadID'+IntToStr(ThreadID)+' '+inttostr(MainForm.label2.tag);
end;
procedure TDownTread.updatalabe3;
begin
MainForm.label3.tag:=MainForm.label3.tag+1;
MainForm.label3.caption:='ThreadID'+IntToStr(ThreadID)+' '+inttostr(MainForm.label3.tag);
end;
end.
这是直接利用socket编程,但是阻塞如何超时退出呢?