1.流程
解决版本问题->设置监听端口和地址->bind,完成后在系统进行监听->循环进行recvfrom接受连接并接受信息
2.简单示例
服务端:
// udp服务端.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<WinSock2.h> #include <stdio.h> #include <Windows.h> #pragma comment(lib,"ws2_32.lib") int main() { WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData)) { printf("版本错误 "); return -1; } int len=sizeof(sockaddr); char recvBuffer[1024]; SOCKET server_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); //SOCKET client_socket; SOCKADDR_IN bind_addr; SOCKADDR_IN client_addr; bind_addr.sin_addr.S_un.S_addr = htonl(ADDR_ANY); bind_addr.sin_port = htons(8888); bind_addr.sin_family = AF_INET; //udp进行bind后开始进行侦听 if (bind(server_socket, (const sockaddr*)&bind_addr, sizeof(sockaddr)) == SOCKET_ERROR) { printf("bind error code is %d ", WSAGetLastError()); return -1; } __try { while (1) { memset(recvBuffer, 0, 1024); recvfrom(server_socket, recvBuffer, 1024, 0, (sockaddr*)&client_addr, &len); printf("receive %s from %s %d ", recvBuffer, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); } } __except (closesocket(server_socket)) { } WSACleanup(); return 0; }
客户端
#include<WinSock2.h> #include<stdio.h> #include<string.h> #pragma comment(lib,"ws2_32.lib") void main() { WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData)) { printf("版本错误 "); return; } int len = 0; char sendBuffer[1024]; SOCKET client_socket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); SOCKADDR_IN client_addr; client_addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); client_addr.sin_family = AF_INET; client_addr.sin_port = htons(8888); printf("info : type quit to quit "); while (1) { memset(sendBuffer, 0, 1024); printf("输入内容: "); scanf("%s", sendBuffer); if (strcmp(sendBuffer, "quit")==0) { printf("quit! "); closesocket(client_socket); WSACleanup(); return; } sendto(client_socket, sendBuffer, strlen(sendBuffer), 0, (const SOCKADDR*)&client_addr, &len); } }