D
driby
Unregistered / Unconfirmed
GUEST, unregistred user!
我在编写winsock程序时,使用CreateThead创建线程老是出错,程序如下:
procedure ClientThread(lpParamointer); //该进程只是从客户端接收数据
var
sock:TSOCKET;
szBuff:array [1..80] of char;
fmtStr:String;
begin
sock:=TSOCKET(lpParam);
while true do
begin
// Perform a blocking recv() call
ret := recv(sock, szBuff, 80, 0);
if ret=0 then // Graceful close
break
else if ret=SOCKET_ERROR then
begin
fmtStr:=Format('recv() failed: %d',[WSAGetLastError()]);
ShowMessage(fmtStr);
break;
end;
fmtStr:='RECV: '+ szBuff;
ShowMessage(fmtStr);
end;
end;
在服务器主程序中调用如下:
var
... ...
fmtStr:String;
wVersionRequested:WORD;
sListen,sClient:TSocket;
hThread:Thandle;
ThreadIDWord;
begin
... ...
while true do
begin
... ...
sClient := accept(sListen, @addr,@iAddrSize);
if sClient = INVALID_SOCKET then
begin
fmtStr:=Format('accept() failed: %d',[WSAGetLastError()]);
Label1.Caption:=fmtStr;
break;
end;
hThread := CreateThread(nil, 0, @ClientThread,@sClient, 0, ThreadID);
if hThread = NULL then
begin
fmtStr:=Format('CreateThread() failed: %d',[GetLastError()]);
Label1.Caption:=fmtStr;
break;
end;
CloseHandle(hThread);
end;
closesocket(sListen);
WSACleanup();
end;
procedure ClientThread(lpParamointer); //该进程只是从客户端接收数据
var
sock:TSOCKET;
szBuff:array [1..80] of char;
fmtStr:String;
begin
sock:=TSOCKET(lpParam);
while true do
begin
// Perform a blocking recv() call
ret := recv(sock, szBuff, 80, 0);
if ret=0 then // Graceful close
break
else if ret=SOCKET_ERROR then
begin
fmtStr:=Format('recv() failed: %d',[WSAGetLastError()]);
ShowMessage(fmtStr);
break;
end;
fmtStr:='RECV: '+ szBuff;
ShowMessage(fmtStr);
end;
end;
在服务器主程序中调用如下:
var
... ...
fmtStr:String;
wVersionRequested:WORD;
sListen,sClient:TSocket;
hThread:Thandle;
ThreadIDWord;
begin
... ...
while true do
begin
... ...
sClient := accept(sListen, @addr,@iAddrSize);
if sClient = INVALID_SOCKET then
begin
fmtStr:=Format('accept() failed: %d',[WSAGetLastError()]);
Label1.Caption:=fmtStr;
break;
end;
hThread := CreateThread(nil, 0, @ClientThread,@sClient, 0, ThreadID);
if hThread = NULL then
begin
fmtStr:=Format('CreateThread() failed: %d',[GetLastError()]);
Label1.Caption:=fmtStr;
break;
end;
CloseHandle(hThread);
end;
closesocket(sListen);
WSACleanup();
end;