//第一种:传指针
TParam=record
TrdId:integer;
Sckt:TSocket;
end;
var
Param:^TParam;
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);
//子线程:
function ChildThrd(p:Pointer):LongInt;stdcall;
var
PkLen:integer;
ThreadId:integer;
ASocket:TSocket;
Temp:TStringList;
buf:array[0..1024] of char;
sendstr,cmd:string;
Handle,ICHandle,ClinicHandle:integer;
m:Double;
bSend:Boolean;
begin
try
while true do
begin
bSend:=True;
Result:=0;
ThreadId:=TParam(p^).TrdId;
ASocket:=TParam(p^).Sckt;
PkLen:=0;
FillChar(buf,SizeOf(buf),0);
PkLen:=Recv(ASocket,buf,SizeOf(buf),0); //接收数据
cmd :=StrPas(buf);
if PkLen>0 then
begin
Form3.Memo1.Lines.Append(cmd);
end;
end;
finally
//CloseSocket(ASocket); //关闭socket
//Dispose(p);
end;
end;
//第二种格式:传地址
s,ns:TSocket;//type:u_int|integer;
pktlen:integer;
server:TSockAddr;//tpye:sockaddr_in
client:PSockAddr;//type:^sockaddr_in
namelen:PInteger;//type:^Integer;
ThreadID:DWORD;
CreateThread(nil,0,@SocketWorkThread,Pointer(ns),0,ThreadID);
procedure SocketWorkThread(ns:TSocket); stdcall; //stdcall 是必须的,否则接收不到参数
var
recvbuf,sendbuf:array[0..1025] of char;
begin
try
While True do
begin
pktlen:= recv(ns,recvbuf,1024,0); //接收数据
if pktlen<1 then //如果返回值小于1说明连接被断开或者错误
begin
Writeln(ID:+IntToHex(ns,2)+ Exit.);
exit;
end;
StrCopy(sendbuf,#13#10Welcome.#13#10);
send(ns,sendbuf,StrLen(sendbuf),0); //发送回应
end;
except
Writeln(SocketWorkThread error.);
exit;
end;
end;