原来,UDP通信,比我想象中简单的多!
// WindowsSocketServer.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include #include #include #include #include #pragma comment(lib,"Ws2_32.lib")using namespace std;#define PORT 8080#define IP_ADDRESS "172.16.20.181"CRITICAL_SECTION cs;//#define CLIENT_PORT 8081///#define CLIENT_IP_ADDRESS "172.16.20.181"//接收每个客户端连接的处理函数DWORD WINAPI ClientThread(LPVOID lpParameter);//连接和服务器端有连接的客户端DWORD WINAPI ConnectClientsThread(LPVOID lpParameter); int main(int argc, char* argv[]) { //版本协商 WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD( 1, 1 ); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { /* Tell the user that we could not find a usable */ /* WinSock DLL. */ return 0; } /* Confirm that the WinSock DLL supports 2.2.*/ /* Note that if the DLL supports versions greater */ /* than 2.2 in addition to 2.2, it will still return */ /* 2.2 in wVersion since that is the version we */ /* requested. */ if ( LOBYTE( wsaData.wVersion ) != 1 || HIBYTE( wsaData.wVersion ) != 1) { /* Tell the user that we could not find a usable */ /* WinSock DLL. */ WSACleanup( ); return 0; } /* The WinSock DLL is acceptable. Proceed. */ //创建数据报套接字 SOCKET svr = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); //创建本地地址信息 SOCKADDR_IN addr; addr.sin_family = AF_INET; addr.sin_port = htons(6000); addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY); int len = sizeof(sockaddr); int bindflag = bind(svr,(sockaddr*)&addr,len); if( bindflag ==SOCKET_ERROR ) { printf("服务器绑定失败!\n"); system("pause"); return 0; } else { printf("服务器端绑定完成。\n"); } //创建客户端地址对象 SOCKADDR_IN addrClient; char recvBuf[128]; char sendBuf[128]; char tempBuf[256]; while(true) { //接收数据 recvfrom(svr,recvBuf,128,0,(sockaddr*)&addrClient,&len); char* ipClient = inet_ntoa(addrClient.sin_addr); sprintf(tempBuf,"接收来自客户端 %s 的数据: %s\n",ipClient,recvBuf); printf("%s",tempBuf); gets_s(sendBuf); //发送数据 sendto(svr,sendBuf,strlen(sendBuf)+1,0,(sockaddr*)&addrClient,len); } closesocket(svr); WSACleanup(); return 0; }
// WindowsSocketClient.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include #include #include #include #include