#include <stdio.h> #include <winsock2.h> #pragma comment(lib, "WS2_32") // 链接到WS2_32.lib class CInitSock { public: CInitSock(BYTE minorVer = 2, BYTE majorVer = 2) { // 初始化WS2_32.dll WSADATA wsaData; WORD sockVersion = MAKEWORD(minorVer, majorVer); if(::WSAStartup(sockVersion, &wsaData) != 0) { exit(0); } } ~CInitSock() { ::WSACleanup(); } }; CInitSock initSock; // 初始化Winsock库 int main1(); int main2(); void main() { printf("Please select a item:/n"); printf("s:Server/n"); printf("c:Client/n"); char a; while(1){ scanf("%c",&a); if(a=='s'){main1();break;} else if(a=='c'){main2();break;} else continue; } } ///服务器绑定后,每从客户端接收一次数据,就输出一次数据;向客户端发送数据 ///客户端向服务器端,发送一次数据;接收服务器发来的数据 //Server int main1() { // 创建套节字 SOCKET s = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(s == INVALID_SOCKET) { printf("Failed socket() /n"); return 0; } // 填充sockaddr_in结构 sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(4567); sin.sin_addr.S_un.S_addr = INADDR_ANY; // 绑定这个套节字到一个本地地址 if(::bind(s, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) { printf("Failed bind() /n"); return 0; } // 接收数据 char buff[1024]; sockaddr_in addr; int nLen = sizeof(addr); while(TRUE) { //从客户端接收数据 int nRecv = ::recvfrom(s, buff, 1024, 0, (sockaddr*)&addr, &nLen); if(nRecv > 0) { buff[nRecv] = '/0'; printf(" 接收到数据(%s):%s", ::inet_ntoa(addr.sin_addr), buff); } //向客户端发送数据 char szText[] = "Server sendto Client! /r/n"; ::sendto(s, szText, strlen(szText), 0, (sockaddr*)&addr, sizeof(addr)); } ::closesocket(s); } //Client int main2() { // 创建套节字 SOCKET s = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(s == INVALID_SOCKET) { printf("Failed socket() %d /n", ::WSAGetLastError()); return 0; } // 也可以在这里调用bind函数绑定一个本地地址 // 否则系统将会自动安排 // 填写远程地址信息 sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(4567); // 注意,这里要填写服务器程序所在机器的IP地址 // 如果你的计算机没有联网,直接使用127.0.0.1即可 addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); // 向服务器端发送数据 char szText[] = "Client sendto UDP Server! /r/n"; ::sendto(s, szText, strlen(szText), 0, (sockaddr*)&addr, sizeof(addr)); //接收来自服务器的数据 char buff[1024]; int nLen = sizeof(addr); int nRecv = ::recvfrom(s, buff, 1024, 0, (sockaddr*)&addr, &nLen); if(nRecv > 0) { buff[nRecv] = '/0'; printf(" 接收到数据(%s):%s", ::inet_ntoa(addr.sin_addr), buff); } ::closesocket(s); return 0; }