一个最简单的UDP通信
生活随笔
收集整理的這篇文章主要介紹了
一个最简单的UDP通信
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
貼在這里主要是做測試代碼時直接從這里拷貝,省的一行行去寫
服務器:
#include "stdafx.h" #include "stdio.h" #include "Winsock2.h" #include "iostream" #include "string" #pragma comment(lib,"WS2_32.lib")#define OK_STR "OK" void main() {int version_a = 1;int version_b = 1;WORD versionRequest = MAKEWORD(version_a, version_b);WSAData wsaData;int err = WSAStartup(versionRequest, &wsaData);if (err != 0){printf("ERROR!");return;}if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1){printf("WRONG WINSOCK VERSION!");WSACleanup();return;}SOCKET socServer = socket(AF_INET, SOCK_DGRAM, 0);SOCKADDR_IN addr_Srv;addr_Srv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);addr_Srv.sin_family = AF_INET;addr_Srv.sin_port = htons(28080);bind(socServer, (SOCKADDR*)&addr_Srv, sizeof(SOCKADDR));SOCKADDR_IN addr_Clt;char recvBuf[100];int fromlen = sizeof(SOCKADDR);while (true){recvfrom(socServer, recvBuf, 100, 0, (SOCKADDR*)&addr_Clt, &fromlen);std::cout << recvBuf << ":" << addr_Clt.sin_port << std::endl;sendto(socServer, OK_STR, strlen(OK_STR) + 1, 0, (SOCKADDR*)&addr_Clt, sizeof(SOCKADDR));}closesocket(socServer);WSACleanup(); }客戶端:
#include "stdafx.h" #include "Winsock2.h" #include "iostream" #include "stdio.h" #pragma comment(lib, "ws2_32.lib") void main() {int version_a = 1;int version_b = 1;WORD versionRequest = MAKEWORD(version_a, version_b);WSAData wsaData;int error = WSAStartup(versionRequest, &wsaData);if (error != 0){printf("ERROR!");return;}if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1){printf("WRONG WINSOCK VERSION!");WSACleanup();return;}char requestStr[100];SOCKET socClient = socket(AF_INET, SOCK_DGRAM, 0);SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr = inet_addr("47.94.155.26");//47.94.155.26192.168.1.117addrSrv.sin_family = AF_INET;addrSrv.sin_port = htons(28080);char cRecvBuf[100];while (true){std::cin >> requestStr;sendto(socClient, requestStr, strlen(requestStr) + 1, 0, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)); recv(socClient, cRecvBuf, strlen(cRecvBuf) + 1, 0);std::cout << cRecvBuf << std::endl;}closesocket(socClient);WSACleanup();// return 0; }總結
以上是生活随笔為你收集整理的一个最简单的UDP通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CreateProcess启动游戏注入D
- 下一篇: protobuf入门教程(一):简介和安