Client骨架:
#include <iostream>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")int main()
{//启动Winsock DLLWORD wVersionRequested = MAKEWORD(2, 2);WSADATA lpWSAData;WSAStartup(wVersionRequested, &lpWSAData);//初始化并设置目标套接字地址SOCKADDR_IN saddr{ 0 };saddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");saddr.sin_family = AF_INET;saddr.sin_port = htons(50123);//本进程创建一个套接字,类型为UDPSOCKET sClient = socket(AF_INET, SOCK_DGRAM, 0);//设置本进程套接字的选项,使其可以重用地址char bOptVal = FALSE;int bOptLen = sizeof(BOOL);setsockopt(sClient, SOL_SOCKET, SO_REUSEADDR, &bOptVal, bOptLen);char buffer[MAX_PATH]{ 0 };int length = sizeof(saddr);while (true){scanf_s("%s", buffer, sizeof(buffer)/sizeof(char));//通过本进程的套接字sRet,把buffer发送到目标套接字sendto(sClient, buffer, sizeof(buffer), 0, (sockaddr*)&saddr, sizeof(saddr));memset(buffer, 0, sizeof(buffer));recvfrom(sClient, buffer, sizeof(buffer), 0, (PSOCKADDR)&saddr, &length);printf("Seriver:%s\n", buffer);}//清理closesocket(sClient);WSACleanup();system("pause");return 0;
}
Service骨架:
#include <iostream>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")int main()
{//启动Winsock DLLWORD wVersionRequested = MAKEWORD(2, 2);WSADATA lpWSAData;WSAStartup(wVersionRequested, &lpWSAData);//初始化并设置本进程套接字地址SOCKADDR_IN saddr{ 0 };saddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);saddr.sin_family = AF_INET;saddr.sin_port = htons(50123);//本进程创建一个套接字,类型为UDPSOCKET sService = socket(AF_INET, SOCK_DGRAM, 0);//设置本进程套接字的选项,使其可以重用地址char bOptVal = FALSE;int bOptLen = sizeof(BOOL);setsockopt(sService, SOL_SOCKET, SO_REUSEADDR, &bOptVal, bOptLen);//将sock地址与本进程套接字绑定bind(sService, (PSOCKADDR)&saddr, sizeof(saddr));char buffer[MAX_PATH]{ 0 };int length = sizeof(saddr);while (true){if (recvfrom(sService, buffer, sizeof(buffer), 0, (PSOCKADDR)&saddr, &length) != -1){printf("Client:%s\n", buffer);strcpy_s(buffer, sizeof(buffer), inet_ntoa(saddr.sin_addr));printf("IP:%s\t端口:%d", buffer,saddr.sin_port);sendto(sService, "收到", strlen("收到"), 0, (PSOCKADDR)&saddr, length);}}closesocket(sService);WSACleanup();system("pause");return 0;
}