当前位置:我的异常网» C语言 » 怎么使用windows网络编程select
怎么使用windows网络编程select
www.myexceptions.net 网友分享于:2015-08-26 浏览:4次
如何使用windows网络编程select?
懂的话,这些代码不难理解,主要功能是实现服务器和客户端的异步通讯,但是运行的时候却做不到(通讯还是异步的),求解?
代码:
server.cpp
#include
#include
#include
#define SERVER_PORT 9999
#define SERVER_IP "127.0.0.1"
int main(int argc,char *argv[])
{
SOCKET serSocket,cliSocket;
struct sockaddr_in localAddr,clientAddr;
WSADATA Ws;
int Bit;
int Lit;
char recvBuf[1024];
int recvR,sen;
int cliLen;
fd_set rfds;//
struct timeval time;//
int maxrd=0;//
int ret;//
if(WSAStartup(MAKEWORD(2,2),&Ws)!=0)
{
printf("init windows socket failed:%d\n",GetLastError());
return -1;
}
serSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(serSocket==INVALID_SOCKET)
{
printf("create socket failed:%d\n",GetLastError());
return -1;
}
localAddr.sin_family=AF_INET;
localAddr.sin_port=htons(SERVER_PORT);
localAddr.sin_addr.s_addr=inet_addr(SERVER_IP);
memset(localAddr.sin_zero,0x00,8);
Bit=bind(serSocket,(struct sockaddr*)&localAddr,sizeof(localAddr));
if(Bit!=0)
{
printf("bind failed:%d\n",GetLastError());
return -1;
}
Lit=listen(serSocket,5);
if(Lit!=0)
{
printf("listen failed:%d\n",GetLastError());
return -1;
}
printf("server has been startup\n");
while(true)
{
cliLen=sizeof(clientAddr);
cliSocket=accept(serSocket,(struct sockaddr*)&clientAddr,&cliLen);
if(cliSocket==INVALID_SOCKET)
{
printf("accept failed:%d\n",GetLastError());
return -1;
}
printf("client connect%d:%d\n",inet_ntoa(clientAddr.sin_addr),clientAddr.sin_port);/
while(true)
{
FD_ZERO(&rfds);///
FD_SET(0,&rfds);
FD_SET(cliSocket,&rfds);
time.tv_sec=1;
time.tv_usec=0;/
maxrd=(maxrd>cliSocket?maxrd:cliSocket);/
ret=select(maxrd+1,&rfds,NULL,NULL,&time);
if(ret==0)//
continue;
else{
if(FD_ISSET(0,&rfds))
{/
memset(recvBuf,0x00,sizeof(recvBuf));
recvR=recv(cliSocket,recvBuf,1024,0);
if(recvR==0||recvR==SOCKET_ERROR)
{
printf("the client had quit\n");
break;
}
printf("recieve message:%s\n",recvBuf);
}
if(FD_ISSET(cliSocket,&rfds))
{
memset(recvBuf,0x00,sizeof(recvBuf));
gets(recvBuf);
sen=send(cliSocket,recvBuf,1024,0);
}
}
}
return 0;
}
closesocket(serSocket);
closesocket(cliSocket);
WSACleanup();
return 0;
}
client.cpp
#include
#include
#include
#define SERVERPORT 9999
#define SERVERIP "127.0.0.1"
int
main(int argc,char* argv[])
{
struct sockaddr_in serAddr;
SOCKET cliSocket;
int conn;
WSADATA Ws;
char sendBuf[1024];
int sen;
int recvR;
fd_set rfds;/
struct timeval time;///
int maxrd=0;
int ret;/
if(WSAStartup(MAKEWORD(2,2),&Ws)!=0)
{
文章评论