用线程创建Socket的连接(内附线程程序)(100分)

Q

qiuying

Unregistered / Unconfirmed
GUEST, unregistred user!
unit Unit2;
interface
uses
Classes,SConnect, SysUtils, Variants;
type
TimerLimit = class(TThread)
private
Socket:TSocketConnection;
Address:String;
protected
procedure Execute;
override;
public
constructor Create(PSocket: TSocketConnection;
PAddress:string);
destructor Destroy;override;
end;
implementation
{ TimerLimit }
constructor TimerLimit.Create(PSocket: TSocketConnection;
PAddress: string);
begin
Socket := PSocket;
Address := PAddress;
FreeOnTerminate := True;
inherited create(false);
end;
destructor TimerLimit.Destroy;
begin
inherited destroy;
end;
procedure TimerLimit.Execute;
begin
FreeOnTerminate :=true ;
Socket.Create(nil);
Socket.Address :=address;
Socket.Port := 211;
if not Socket.Connected then
try
Socket.Connected :=true;
except
Terminate ;
end;
end;
end.

//主程序
procedure TForm1.BitBtn3Click(Sender: TObject);
begin
SocketConnection1.Connected :=false;

TimerLimit.Create(SocketConnection1,edit1.text)
// OnTerminate:= ThreadDone;
end;
第一次可以连接,再连接是会报“ACCESS violation at address...”错误信息。请大家帮忙看一下是什么问题
 
procedure TimerLimit.Execute;
begin
FreeOnTerminate :=true ;
//去了这行
//// Socket.Create(nil);
Socket.Address :=address;
Socket.Port := 211;
if not Socket.Connected then
try
Socket.Connected :=true;
except
Terminate ;
end;
end;
 
用法完全错误,
首先,Create不是那样用的,按你的程序来看,SocketConnection在主线程中已经创建,
不需要创建,如果要在线程内创建就不用传那个参数,直接在
constructor TimerLimit.Create(PSocket: TSocketConnection;
PAddress: string);
begin
Socket := TSocketConnection.Create( Nil );
...
其次,你这样是把主线程的SocketConnection给子线程用,如果有多个子线程运行的话
后果就是...
 
Socket.Create(nil)改为Socket := TSocketConnection.Create(nil);
 
要注意将Socket连接关闭,
用了多个线程的话要进行同步!!!
 
顶部