windows 网络编程(四)---UDP对话的实现
次程序只能实现一问一答的模式聊天,要实现随机性聊天貌似要用到线程
参考资料http://www.cnblogs.com/qxhcpp/archive/2012/04/27/2473756.html
服务端:
#include <Winsock2.h> #include <stdio.h> void main() { WORD wVersionRequested;//定义一个word类型的变量 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; } SOCKET socksrv=socket(AF_INET,SOCK_DGRAM,0); SOCKADDR_IN addrsrv; addrsrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY); addrsrv.sin_family=AF_INET; addrsrv.sin_port=htons(6000); bind(socksrv,(SOCKADDR*)&addrsrv,sizeof(SOCKADDR)); char recvBuf[100]; char sendBuf[100]; char tempBuf[200]; SOCKADDR_IN addrClient; int len=sizeof(SOCKADDR); while(1) { recvfrom(socksrv,recvBuf,100,0,(SOCKADDR*)&addrClient,&len); if('q'==recvBuf[0])//判断如果第一个字符是Q则退出 { sendto(socksrv,"q",strlen("q")+1,0,(SOCKADDR*)&addrClient,len); printf("chat end !\n"); break; } sprintf(tempBuf,"%s say:%s",inet_ntoa(addrClient.sin_addr),recvBuf); //如果不是Q则将客户端的IP地址和发送的数据格式化完放到tempBUf中 printf("%s\n",tempBuf); printf("please input data:\n"); //等待用户输入 gets(sendBuf);//从标准输入流中获取一行数据 sendto(socksrv,sendBuf,strlen(sendBuf)+1,0,(SOCKADDR*)&addrClient,len); //将用户输入的数据发送到客户端 } closesocket(socksrv); WSACleanup(); }
客户端:
#include <Winsock2.h> #include <stdio.h> void main() { WORD wVersionRequested;//定义一个word类型的变量 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; } SOCKET sockClient=socket(AF_INET,SOCK_DGRAM,0); SOCKADDR_IN addrsrv; addrsrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); addrsrv.sin_family=AF_INET; addrsrv.sin_port=htons(6000); char recvBuf[100]; char sendBuf[100]; char tempBuf[200]; int len=sizeof(SOCKADDR); sendto(sockClient,"start",strlen("start")+1,0, (SOCKADDR*)&addrsrv,len); while(1) { //等待服务器端的回应 recvfrom(sockClient,recvBuf,100,0, (SOCKADDR*)&addrsrv,&len); if('q'==recvBuf[0]) { sendto(sockClient,"q",strlen("q")+1,0, (SOCKADDR*)&addrsrv,len); printf("chat end!\n"); break; } sprintf(tempBuf,"%s say :%s",inet_ntoa(addrsrv.sin_addr),recvBuf); printf("%s\n",tempBuf); printf("please input data:\n"); gets(sendBuf); sendto(sockClient,sendBuf,strlen(sendBuf)+1,0, (SOCKADDR*)&addrsrv,len); } closesocket(sockClient); WSACleanup(); }