服务器端:
// UdpSrv.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <Winsock2.h> //必须加载套接字的头文件,还必须在工程的链接处添加 Ws2_32.lib #include <stdio.h> int main(int argc, char* argv[]) { //加载套接字库 WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested =MAKEWORD(1,1); err =WSAStartup(wVersionRequested,&wsaData ); if(err!=0) { return 0; } if(LOBYTE(wsaData.wVersion)!=1 || HIBYTE(wsaData.wVersion)!=1 ) { WSACleanup (); return 0; } //创建套接字 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[100]; SOCKADDR_IN addrClient ; int len =sizeof(SOCKADDR); while(1) { recvfrom(sockSrv,recvBuf,100,0,(SOCKADDR *) &addrClient,&len); if('q'==recvBuf[0]) { sendto(sockSrv,"q",strlen("q")+1,0,(SOCKADDR *)&addrClient,len); printf("chat end! "); break; } sprintf(tempBuf,"%s say : %s",inet_ntoa(addrClient.sin_addr),recvBuf); printf("%s ",tempBuf); //send data printf("please input data: "); gets(sendBuf); sendto(sockSrv,sendBuf,strlen(sendBuf)+1,0,(SOCKADDR *)&addrClient,len); } //关闭套接字 WSACleanup(); return 0; }
客户端:
// UdpClient.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <Winsock2.h> //必须加载套接字的头文件,还必须在工程的链接处添加 Ws2_32.lib #include <stdio.h> int main(int argc, char* argv[]) { //加载套接字库 WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested =MAKEWORD(1,1); err =WSAStartup(wVersionRequested,&wsaData ); if(err!=0) { return 0; } if(LOBYTE(wsaData.wVersion)!=1 || HIBYTE(wsaData.wVersion)!=1 ) { WSACleanup (); return 0; } //创建套接字 SOCKET sockClient =socket(AF_INET,SOCK_DGRAM,0); SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr =inet_addr("219.244.93.95"); addrSrv.sin_family =AF_INET; addrSrv.sin_port =htons(6000); char recvBuf[100]; char sendBuf[100]; char tempBuf[100]; int len =sizeof(SOCKADDR); while(1) { //send data printf("please input data: "); gets(sendBuf); sendto(sockClient,sendBuf,strlen(sendBuf)+1,0,(SOCKADDR *)&addrSrv,len); 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! "); break; } sprintf(tempBuf,"%s say : %s",inet_ntoa(addrSrv.sin_addr),recvBuf); printf("%s ",tempBuf); } //关闭套接字 closesocket (sockClient); WSACleanup(); return 0; }
基于tcp的多一个链接过程。