新学的,有错误请指出

bool InitialSocket(SOCKET sock,u_short port);
int FindPosOfSet(SOCKET s,fd_set * set);
 
int _tmain(int argc, _TCHAR* argv[])
{
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2,2),&wsaData);
 
	SOCKET sListen=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
 
	if(!InitialSocket(sListen,25418))
	{
		printf("Socket initial Error!\n");
		return -1;
	}
 
	fd_set fdset;
	FD_ZERO(&fdset);
	FD_SET(sListen,&fdset);
 
	int nRet=0;
	char buf[100];
	ZeroMemory(buf,sizeof(buf));
 
	printf("waiting for new connection!\n");
 
	while(true)
	{
		
		fd_set fdread=fdset;
		//fd_set fdwrite=fdset;
		
		nRet=select(NULL,&fdread,NULL,NULL,NULL);
 
		if(nRet>0)
		{
			//循环遍历每个在fdread中的SOCKET
			for(unsigned int i=0;i<fdread.fd_count;++i)
			{
				if(fdread.fd_array[i]==sListen)
				{
					//有客户端接入
					SOCKADDR_IN newAddr;
					int len=sizeof(SOCKADDR);
					SOCKET newSocket=accept(sListen,(SOCKADDR*)&newAddr,&len);
					if(newSocket==INVALID_SOCKET)
					{
						printf("INVALID SOCKET|Error code:%d\n",WSAGetLastError());
						goto CLEAN;
					}
					//将接入的SOCKET放入SET
					FD_SET(newSocket,&fdset);
					printf("add new connection:%s\nnow %d client(s) online\n",inet_ntoa(newAddr.sin_addr),fdset.fd_count-1);
				}
				else
				{
					//有数据可读
 
					//判断SOCKET是否断开
					ZeroMemory(buf,sizeof(buf));
					
					if(recv(fdread.fd_array[i],buf,100,0)==0)
					{
						printf("Client disconnect!\n");
						//将断开SOCKET从SET中删除
						FD_CLR(fdread.fd_array[i],&fdset);
						continue;
					}
					printf("recving data from %d :%s\n",FindPosOfSet(fdread.fd_array[i],&fdset),buf);
				}
			}
		}
		else
		{
			printf("nret==0!\n");
		}
	}
	closesocket(sListen);
	WSACleanup();
	return 0;
 
 
CLEAN:	{
	closesocket(sListen);
		WSACleanup();
		return -1;
	}
}
 
bool InitialSocket(SOCKET sock,u_short port)
{
// 	WSADATA wsaData;
// 	WSAStartup(MAKEWORD(2,2),&wsaData);
 
	SOCKADDR_IN serverAddr;
	serverAddr.sin_family=AF_INET;
	serverAddr.sin_port=htons(port);
	serverAddr.sin_addr.s_addr=htonl(ADDR_ANY);
 
	if(bind(sock,PSOCKADDR(&serverAddr),sizeof(serverAddr)))
	{
		printf("bind error!error code:%d\n",WSAGetLastError());
		WSACleanup();
		return false;
	}
 
	if(listen(sock,5))
	{
		printf("listen error!error code:%d\n",WSAGetLastError());
		WSACleanup();
		return false;
	}
 
	return true;
}
 
int FindPosOfSet(SOCKET s,fd_set * set)
{
	for(int i=0;i<set->fd_count;++i)
	{
		if(s==set->fd_array[i])
		{
			return i;
		}
	}
}

共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day