服务器端Code:
// UdpSrv.cpp
// dxh1688@gmail.com
#include <Winsock2.h>
#include <stdio.h>
void main()
{
//加载套接字库(该部分代码可重用,直接复制即可。)
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(1, 1);
err = WSAStartup(wVersionRequested, &wsaData);
if (0 != err) {
return;
}
if (1 != LOBYTE(wsaData.wVersion) ||
1 != HIBYTE(wsaData.wVersion)) {
WSACleanup();
return;
}
//创建套接字
SOCKET sockSrv = socket(AF_INET, SOCK_DGRAM, 0);
//绑定套接字
SOCKADDR_IN addrSrc;
addrSrc.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrSrc.sin_family = AF_INET;
addrSrc.sin_port = htons(6000);
bind(sockSrv, (SOCKADDR *)&addrSrc, sizeof(SOCKADDR));
//等待并接收数据
SOCKADDR_IN addrClient;
int len = sizeof(SOCKADDR);
char recvBuf[100];
recvfrom(sockSrv, recvBuf, 100, 0, (SOCKADDR *)&addrClient, &len);
printf("%s", recvBuf);
//关闭套接字
closesocket(sockSrv);
WSACleanup();
getchar();
}
客户端Code:
// UdpClient.cpp
// dxh1688@gmail.com
#include <Winsock2.h>
#include <stdio.h>
void main()
{
//加载套接字库(该部分代码可重用,直接复制即可。)
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD(1, 1);
err = WSAStartup(wVersionRequested, &wsaData);
if (0 != err) {
return;
}
if (1 != LOBYTE(wsaData.wVersion) ||
1 != HIBYTE(wsaData.wVersion)) {
WSACleanup();
return;
}
//创建套接字
SOCKET sockClient = socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(6000);
//发送数据
sendto(sockClient, "I am Deng!", sizeof("I am Deng!") + 1, 0, (SOCKADDR *)&addrSrv, sizeof(SOCKADDR));
//关闭套接字
closesocket(sockClient);
WSACleanup();
getchar();
}