我有这个套接字程序,它具有发送和接收的两个部分,但是当我使用 select 时,它总是返回“时间错误”。这是代码
void server::run(){
int RetVal;
struct timeval *tp=new timeval;
tp->tv_sec=300;
tp->tv_usec=500000;
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(sock,&readfds);
FD_SET(sock1,&readfds);
cout<<"run() is working fine";
if((RetVal=select(1,&readfds,NULL,NULL,tp))==SOCKET_ERROR) //check for incoming packets.
{
cout<< "Timer error!";
Sleep(50);
}
else if(RetVal>0) //There are incoming packets.
{
if(FD_ISSET(sock1, &readfds)) //incoming packet from peer host 1
{
send();
}
else if(FD_ISSET(sock, &readfds)) //incoming packet from peer host 1
{
send1();
}
else{
cout<<"no port is open to communicate";
}
}
}
server::server(){
WSADATA wsadata;
try{
if (WSAStartup(0x0202,&wsadata)!=0)
throw"Starting WSAStartup() error\n";
//Display name of local host
if(gethostname(servername,HOSTNAME_LENGTH)!=0) //get the hostname
throw"Get the host name error,exit";
}
catch(char *str){
cerr<<str<<":"<<WSAGetLastError()<<endl;
}
printf("Server: %s waiting to be contacted for time/size request...\n",servername);
}
server::~server(){
WSACleanup();
}
void server::send(){
try{
if ((sock= socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR)
{
cout<< "SERVER: socket unable to initialize\n";
}
servers.sin_family = AF_INET;
servers.sin_port = htons(port);
servers.sin_addr.s_addr = INADDR_ANY;
if (bind(sock, (sockaddr*)&servers, sizeof(servers)) == SOCKET_ERROR)
{
cout<<"SERVER: Cant Bind the Socket";
closesocket(sock);
}
if (listen(sock, MAXPENDING) == SOCKET_ERROR)
//if((value=listen(sock, MAXPENDING))==SOCKET_ERROR)
{
cout<<"SERVER: listening socket not open";
closesocket(sock);
}
if ((clientSock= accept(sock, 0, 0)) == SOCKET_ERROR)
{
throw"SERVER: connection not accepted";
}
if ((nBytes= send(clientSock, "Hello", 20, 0)) == SOCKET_ERROR)
{
throw"SERVER: data sending failed ";
}
}
catch(char *str){
cerr<<str<<":"<<WSAGetLastError()<<endl;
}
closesocket(clientSock);
closesocket(sock);
}
void server::send1(){
try{
if ((sock1= socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR)
{
throw "SERVER: socket unable to initialize\n";
}
servers.sin_family = AF_INET;
servers.sin_port = htons(port);
servers.sin_addr.s_addr = INADDR_ANY;
if (bind(sock1, (sockaddr*)&servers, sizeof(servers)) == SOCKET_ERROR)
{
throw"SERVER: Cant Bind the Socket";
closesocket(sock1);
}
if (listen(sock1, MAXPENDING) == SOCKET_ERROR)
{
throw "SERVER: listening socket not open";
closesocket(sock1);
}
cout << "SERVER: Ready to run now...";
if ((clientSock= accept(sock1, 0, 0)) == SOCKET_ERROR)
{
throw"SERVER: connection not accepted";
}
if ((nBytes= send(clientSock, "Hello", 20, 0)) == SOCKET_ERROR)
{
throw"SERVER: data sending failed ";
}
}
catch(char *str){
cerr<<str<<":"<<WSAGetLastError()<<endl;
}
closesocket(clientSock);
closesocket(sock1);
}
我尝试了很多东西,但我的 select() 总是返回同样的东西。如果我直接调用 send 和 recv(),我的程序在没有 run() 和 select() 的情况下工作正常。但我猜 select() 不起作用。