// UDPServer.cpp
#include <
stdio.h
>
#include <
WINSOCK2.H
>
#pragma comment(lib,"WS2_32.lib")
#define BUF_SIZE 64
int main(void)
{
WSADATA wsd;
SOCKET s;
int nRet;
// 初始化套接字动态库
if(WSAStartup(MAKEWORD(2,2),&wsd) != 0)
{
printf("WSAStartup failed !\n");
return 1;
}
// 创建套接字
s = socket(AF_INET,SOCK_DGRAM,0);
if(s == INVALID_SOCKET)
{
printf("socket() failed ,Error Code:%d\n",WSAGetLastError());
WSACleanup();
return 1;
}
SOCKET socketSrv = socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN addrSrv;
SOCKADDR_IN addrClient;
char buf[BUF_SIZE];
int len = sizeof(SOCKADDR);
// 设置服务器地址
ZeroMemory(buf,BUF_SIZE);
addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(5000);
// 绑定套接字
nRet = bind(socketSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
if(SOCKET_ERROR == nRet)
{
printf("bind failed !\n");
closesocket(s);
WSACleanup();
return -1;
}
// 从客户端接收数据
nRet = recvfrom(socketSrv,buf,BUF_SIZE,0,(SOCKADDR*)&addrClient,&len);
if(SOCKET_ERROR == nRet)
{
printf("recvfrom failed !\n");
closesocket(s);
WSACleanup();
return -1;
}
// 打印来自客户端发送来的数据
printf("Recv From Client:%s\n",buf);
// 向客户端发送数据
sendto(socketSrv,"UDP Hello World !",sizeof("UDP Hello World !"),0,(SOCKADDR*)&addrClient,len);
closesocket(s);
WSACleanup();
return 0;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
//////////////////////////////////////////////////////////////////////////
// UDPClient.cpp
#include <
stdio.h
>
#include <
WINSOCK2.H
>
#pragma comment(lib,"WS2_32.lib")
#define BUF_SIZE 64
int main(void)
{
WSADATA wsd;
SOCKET s;
// 初始化套接字动态库
if(WSAStartup(MAKEWORD(2,2),&wsd) != 0)
{
printf("WSAStartup failed !\n");
return 1;
}
// 创建套接字
s = socket(AF_INET,SOCK_DGRAM,0);
if(s == INVALID_SOCKET)
{
printf("socket() failed, Error Code:%d\n",WSAGetLastError());
WSACleanup();
return 1;
}
char buf[BUF_SIZE]; // 接受数据
SOCKADDR_IN servAddr; // 服务器套接字地址
SOCKET sockClient = socket(AF_INET,SOCK_DGRAM,0);
int nRet;
ZeroMemory(buf,BUF_SIZE);
strcpy(buf,"UDP Hello World !");
// 设置服务器地址
servAddr.sin_family = AF_INET;
servAddr.sin_addr.S_un.S_addr = inet_addr("192.168.1.254");
servAddr.sin_port = htons(5000);
// 向服务器发送数据
int nServAddLen = sizeof(servAddr);
if(sendto(sockClient,buf,BUF_SIZE,0,(sockaddr *)&servAddr,nServAddLen) == SOCKET_ERROR)
{
printf("recvfrom() failed:%d\n",WSAGetLastError());
closesocket(s);
WSACleanup();
return 1;
}
nRet = recvfrom(sockClient,buf,BUF_SIZE,0,(sockaddr *)&servAddr,&nServAddLen);
if(SOCKET_ERROR == nRet)
{
printf("recvfrom failed !\n");
closesocket(s);
WSACleanup();
return -1;
}
// 打印来自服务端发送来的数据
printf("Recv From Server:%s\n",buf);
closesocket(s);
WSACleanup();
return 0;
}
|