求助:vc++下,winsock编程,为什么accept函数不能阻塞进程?(内附代码和说明)
运行起来后,屏幕持续地输出乱码#include<Winsock2.h>#include<stdio.h>#include<windows.h>#include<iostr...
运行起来后,屏幕持续地输出乱码
#include <Winsock2.h>
#include <stdio.h>
#include <windows.h>
#include <iostream.h>
class CTrans
{
public:
SOCKET m_sockSrv;
public:
//Constructor
CTrans()
{
//Intiates Ws2_32.dll with WSAStartup
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = ::WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
::WSACleanup( );
return;
}
//
m_sockSrv=::socket(AF_INET,SOCK_STREAM,0);
}
//Deconstructor
~CTrans()
{
closesocket(m_sockSrv);
::WSACleanup();
}
//Bind and Listen
void BindListen()
{
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=::htonl(INADDR_ANY);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=::htons(7673);
addrSrv.sin_zero;
::bind(m_sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
::listen(m_sockSrv,5);
SOCKADDR_IN addrClnt;
int len=sizeof(SOCKADDR);
while(1)
{
SOCKET sockConn=::accept(m_sockSrv,(SOCKADDR*)&addrClnt,&len);
char recvBuf[2048];
::recv(sockConn,recvBuf,2048,0);
::printf("%s",recvBuf);
::closesocket(sockConn);
}
}
};
void main()
{
CTrans trans;
trans.BindListen();
}
试过将accept放到main()中依然是这个问题 展开
#include <Winsock2.h>
#include <stdio.h>
#include <windows.h>
#include <iostream.h>
class CTrans
{
public:
SOCKET m_sockSrv;
public:
//Constructor
CTrans()
{
//Intiates Ws2_32.dll with WSAStartup
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = ::WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
::WSACleanup( );
return;
}
//
m_sockSrv=::socket(AF_INET,SOCK_STREAM,0);
}
//Deconstructor
~CTrans()
{
closesocket(m_sockSrv);
::WSACleanup();
}
//Bind and Listen
void BindListen()
{
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=::htonl(INADDR_ANY);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=::htons(7673);
addrSrv.sin_zero;
::bind(m_sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
::listen(m_sockSrv,5);
SOCKADDR_IN addrClnt;
int len=sizeof(SOCKADDR);
while(1)
{
SOCKET sockConn=::accept(m_sockSrv,(SOCKADDR*)&addrClnt,&len);
char recvBuf[2048];
::recv(sockConn,recvBuf,2048,0);
::printf("%s",recvBuf);
::closesocket(sockConn);
}
}
};
void main()
{
CTrans trans;
trans.BindListen();
}
试过将accept放到main()中依然是这个问题 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询