简单的UDP编程
//Server #include "stdafx.h" #include<WinSock2.h> #include<windows.h> #include<iostream> using namespace std; #pragma comment (lib,"ws2_32.lib") #define PORT 6000 //UDP Server int main() { //初始化网络环境 WSADATA wsa; if (WSAStartup(MAKEWORD(2, 2), &wsa)!=0) { cout << "初始化网络环境失败" << endl; return -1; } //创建UDP的socket SOCKET sServer = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sServer==INVALID_SOCKET) { cout << "创建套接字失败" << endl; return -1; } SOCKADDR_IN si; si.sin_family = AF_INET; si.sin_port = htons(PORT); si.sin_addr.S_un.S_addr = htonl(INADDR_ANY); //开始绑定 bind(sServer, (sockaddr *)&si, sizeof(sockaddr)); printf("Now,Server is running on port 6000,waiting for you\n"); char szbuf[2048]; memset(szbuf, 0, sizeof(szbuf)); while (TRUE) { SOCKADDR_IN siClient; memset(&siClient, 0, sizeof(sockaddr)); int siClientLen = sizeof(sockaddr); int ret = recvfrom(sServer, szbuf, sizeof(szbuf), 0,(sockaddr *) &siClient, &siClientLen); printf("Recv msg:%s from IP[%s],port[%d]\n", szbuf, inet_ntoa(siClient.sin_addr), ntohs(siClient.sin_port)); sendto(sServer,"hello,你好",sizeof("hello,你好"),0, (sockaddr *)&siClient, siClientLen); printf("send back to IP[%s],port[%d]\n", inet_ntoa(siClient.sin_addr), ntohs(siClient.sin_port)); } return 0; } //Client #include "stdafx.h" #include<WinSock2.h> #include<windows.h> #include<iostream> using namespace std; #pragma comment (lib,"ws2_32.lib") #define PORT 6000 //UDP Server int main() { //初始化网络环境 WSADATA wsa; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { cout << "初始化网络环境失败" << endl; return -1; } //创建UDP的socket SOCKET sClient = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sClient == INVALID_SOCKET) { cout << "创建套接字失败" << endl; return -1; } SOCKADDR_IN si; si.sin_family = AF_INET; si.sin_port = htons(PORT); si.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //开始绑定 //bind(sClient, (sockaddr *)&si, sizeof(sockaddr)); char szbuff[] = {"hello i am Client"}; int dwSend = sendto(sClient, szbuff, sizeof(szbuff), 0, (sockaddr *)&si, sizeof(sockaddr)); if (dwSend==0) { cout << "发送失败" << endl; return -1; } cout << "Client Send msg :" << szbuff << endl; char szRecvBuff[2048]; memset(szRecvBuff,0, sizeof(szRecvBuff)); SOCKADDR_IN addrServer = { 0 }; int addrServerLen = sizeof(sockaddr); recvfrom(sClient, szRecvBuff, sizeof(sockaddr), 0, (sockaddr *)&addrServer, &addrServerLen); cout << "Client Recv msg from Serve:" << szRecvBuff << endl; closesocket(sClient); WSACleanup(); return 0; }