/********************************************************************数据报套接字的对等模式实例:首先输入要发送给对方的消息,然后发送给对方,再接收对方发送过来的消息,如此循环地进行发送-接收********************************************************************/#includestring.h#includestdio.h#includewinsock2.h#pragmacomment(lib,Ws2_32.lib)voidmain(){WSADATAwsaData;if(WSAStartup(MAKEWORD(1,1),&wsaData))//调用初始化函数,版本号为1.1{printf(CouldnotloadwindowssocketsDLL\n);return;}//创建数据报套接字SOCKETs=socket(AF_INET,SOCK_DGRAM,0);if(s==INVALID_SOCKET){printf(invalidsocket\n);WSACleanup();return;}//本地地址信息sockaddr_inhostAddress;intaddressLen=sizeof(sockaddr_in);memset((void*)&hostAddress,0,addressLen);//清空sockaddr结构hostAddress.sin_family=AF_INET;//Internet协议族intport;printf(localport(1024-65535):);scanf(%d,&port);hostAddress.sin_port=htons(port);//端口hostAddress.sin_addr.s_addr=INADDR_ANY;//对方地址信息sockaddr_inremoteAddress;memset((void*)&remoteAddress,0,addressLen);//清空sockaddr结构remoteAddress.sin_family=AF_INET;//Internet协议族printf(remoteport(1024-65535):);scanf(%d,&port);remoteAddress.sin_port=htons(port);//对方端口remoteAddress.sin_addr.s_addr=inet_addr(127.0.0.1);//对方IP地址//将本地地址绑定到套接字if(bind(s,(sockaddr*)&hostAddress,addressLen)){printf(bindfailed\n);WSACleanup();return;}charbuf[1024],msg[1024];charmyName[30];printf(请输入您的昵称:);scanf(%s,myName);strcat(myName,:);sockaddr_infromAddress;while(1){printf(请输入要发送的消息:);scanf(%s,msg);strcpy(buf,myName);strcat(buf,msg);//发送数据给对方if(sendto(s,buf,strlen(buf),0,(sockaddr*)&remoteAddress,addressLen)==SOCKET_ERROR){printf(sendto2failed\n);break;}//接收数据并显示intn=recvfrom(s,buf,sizeof(buf),0,(sockaddr*)&fromAddress,&addressLen);if(n0){buf[n]=0;//理解为什么这么做printf(Reveivedfrom%s\n,buf);}elseprintf(erro:%d\n,n);//确保下次是回复给对方if(memcmp(&remoteAddress,&fromAddress,addressLen))memcpy(&remoteAddress,&fromAddress,addressLen);}closesocket(s);WSACleanup();}