accept为何不阻塞?(200分)

  • 主题发起人 主题发起人 acee
  • 开始时间 开始时间
A

acee

Unregistered / Unconfirmed
GUEST, unregistred user!
procedure TForm1.Server3;
var
s,newsock:TSocket;
addrs:TSockAddrIn;
addrc:PSockAddr;
leng:Integer;
wsa:WSAData;
wVersionRequested:WORD;
buf:array[0..128]of char;
buf2:array[0..128]of char;
begin
wVersionRequested := MAKEWORD( 2, 0 );
WSAStartup(wVersionRequested,wsa);

s := socket(AF_INET,SOCK_STREAM,0);
Memo1.Lines.Add('Create Socket Succeed');

addrs.sin_family := AF_INET;
addrs.sin_addr.S_addr := htonl(INADDR_ANY);
addrs.sin_port := htons(12000);

bind(s,addrs,sizeof(addrs));
Memo1.Lines.Add('Bind Socket Succeed');
listen(s,1);
Memo1.Lines.Add('Listen Socket Succeed');
while 1>0 do
begin
leng:= sizeof(addrc);
newsock := accept(s,addrc,@leng);
if newsock >= 0 then
Memo1.Lines.Add('Accept Socket='+ InttoStr(newsock)+ 'succeed!');
if recv(newsock,buf,sizeof(buf),0)>0 then
begin
Form1.Memo1.Lines.Add(buf2);
strcopy(buf2,PChar(form1.Edit1.Text));
send(newsock,buf2,sizeof(buf2),0);
end;
closesocket(newsock);
end;

Closesocket(s);
WSACleanup();
sleep(2000);
end;

在代码 newsock := accept(s,addrc,@leng);处为何没有阻塞等到客户端的连接?请高手指点。谢谢!
 
你的代码没有进行任何错误处理的,填上这些就容易找那里错了
 
不阻塞是好事啊
 
我用断点跟踪过去,发现newsock := accept(s,addrc,@leng);这个地方直接运行过去了,按理来说是要阻塞在这才对的。如果用idtcpclient.readbuff就阻塞了。
 
WSADATA Data;
SOCKADDR_IN serverSockAddr;
SOCKADDR_IN clientSockAddr;
SOCKET serverSocket;
SOCKET clientSocket;

_CheckInData szData;

int addrLen=sizeof(SOCKADDR_IN);
int status;
int numrcv;
char buffer[MAXBUFLEN];

/* initialize the Windows Socket DLL */
status=WSAStartup(MAKEWORD(1, 1), &Data);
if (status != 0) return 0;

memset(&serverSockAddr, 0,sizeof(serverSockAddr));

serverSockAddr.sin_port=htons(PORT);

serverSockAddr.sin_family=AF_INET;

serverSockAddr.sin_addr.s_addr=htonl(INADDR_ANY);

/* create a socket */
serverSocket=socket(AF_INET, SOCK_STREAM, 0);

if (serverSocket == INVALID_SOCKET) return 0;

/* associate the socket with the address */
status=bind(serverSocket, (LPSOCKADDR) &serverSockAddr,sizeof(serverSockAddr));

if (status == SOCKET_ERROR) return 0;

/* allow the socket to take connections */
status=listen(serverSocket, 1);

if (status == SOCKET_ERROR) return 0;

/* accept the connection request when one
is received */


while(1)
{

clientSocket=accept(serverSocket,(LPSOCKADDR) &clientSockAddr,&addrLen);
numrcv=recv(clientSocket, buffer, MAXBUFLEN, NO_FLAGS_SET);

if ((numrcv == 0) || (numrcv == SOCKET_ERROR))
{
status=closesocket(clientSocket);
status=WSACleanup();
break;
}
 
accept(s,addrc,@leng);
第二个参数错误,Addrc应指向一个TSockAddr结构,你的没有初始化,检查一下返回值和
GetLastError的值,就看出来了
 
var
addr : TSockAddrIn;
ClientSocket: TSocket;
addrlen: integer;
begin
fillchar(addr, sizeof(addr), 0);
addrlen := sizeof(addr);
ClientSocket := Accept(FSerSocket, addr, addrlen);
if ClientSocket = INVALID_SOCKET then
begin
closesocket(ClientSocket) ;
exit;
end;
end;
 
想不阻塞就用acceptEx
 
铁盒子说的完全正确,我已经解决了,谢谢你们!
 
多人接受答案了。
 
后退
顶部