C语言 UDP双向通讯仿TCP通讯模式

//SERV端#include #include #pragma comment(lib, "ws2_32.lib") int main(int argc, char* argv[]){ WSADATA wsaData; WORD sockVersion = MAKEWORD(2,2); if(WSAStartup(sockVersion, &wsaData) != 0) { return 0; } SOCKET serSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(serSocket == INVALID_SOCKET) { printf("socket error !"); return 0; } sockaddr_in serAddr; serAddr.sin_family = AF_INET; serAddr.sin_port = htons(8888); serAddr.sin_addr.S_un.S_addr = INADDR_ANY; if(bind(serSocket, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR) { printf("bind error !"); closesocket(serSocket); return 0; } sockaddr_in remoteAddr; int nAddrLen = sizeof(remoteAddr); while (true) { char recvData[255]; int ret = recvfrom(serSocket, recvData, 255, 0, (sockaddr *)&remoteAddr, &nAddrLen); if (ret > 0) { recvData[ret] = 0x00; printf("DD%s \r\n", inet_ntoa(remoteAddr.sin_addr)); printf(recvData); } char * sendData = "DDD\n"; sendto(serSocket, sendData, strlen(sendData), 0, (sockaddr *)&remoteAddr, nAddrLen); } closesocket(serSocket); WSACleanup(); return 0;}客户端#include #include #pragma comment(lib, "ws2_32.lib") int main(int argc, char* argv[]){ WORD socketVersion = MAKEWORD(2,2); WSADATA wsaData; if(WSAStartup(socketVersion, &wsaData) != 0) { return 0; } SOCKET sclient = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(8888); sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); int len = sizeof(sin); char * sendData = "sss.\n"; sendto(sclient, sendData, strlen(sendData), 0, (sockaddr *)&sin, len); char recvData[255]; int ret = recvfrom(sclient, recvData, 255, 0, (sockaddr *)&sin, &len); if(ret > 0) { recvData[ret] = 0x00; printf("recvData=%s\n",recvData); } closesocket(sclient); WSACleanup(); return 0;}

你可能感兴趣的:(C语言)