Winsock编程基础2(UDP流程)
标签:namespace int inet_addr amp 长度 etc its using 需要
UDP用户数据报协议
服务器端
客户端
(closesocket)
int sendto(
SOCKET s, //用来发送数据的套接字
const char FAR *buf, //指向发送数据的缓冲区
int len, //要发送数据长度
int flags, //一般指定0
const struct sockaddr *to, //指向一个包含目标地址和端口号的sockaddr_in结构
int toLen //结构大小
);
int recvfrom(SOCKET s, char *FAR buf, int len, int flags, struct sockaddr FAR *from, int FAR* fromLen)
简单实例
服务器端
#include
#include
#include "InitSock.h"
using namespace std;
int main(void)
{
CInitSock initSock;
//创建套接字
SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
{
cout "Failed socke()" endl;
return 0;
}
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(4567);
addr.sin_addr.S_un.S_addr = INADDR_ANY;
//绑定套接字到一个本地地址
if (bind(s, (LPSOCKADDR)&addr, sizeof(addr)) == SOCKET_ERROR)
{
cout "Failed bind()" endl;
return 0;
}
//接收数据
char buf[1024];
sockaddr_in clientAddr;
int nLen = sizeof(addr);
while (TRUE)
{
int nRecv = recvfrom(s, buf, 1024, 0, (sockaddr*)&clientAddr, &nLen);
if (nRecv > 0)
{
buf[nRecv] = ‘\0‘;
cout "接收到数据" ": " endl;
}
}
//关闭套接字
closesocket(s);
return 0;
}
客户端
#include
#include
#include "InitSock.h"
using namespace std;
int main(void)
{
CInitSock initSock;
//创建套接字
SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
{
cout "Failed socke()" endl;
return 0;
}
//创建套接字之后如果首先sendto可以不绑定
//若首先recvfrom则需要绑定
//填写远程地址信息
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(4567);
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
//发送数据
char szText[] = "UDP Server Demo\r\n";
sendto(s, szText, strlen(szText), 0, (sockaddr*)&addr, sizeof(addr));
closesocket(s);
cout "数据已发送" endl;
getchar();
return 0;
}
Winsock编程基础2(UDP流程)
标签:namespace int inet_addr amp 长度 etc its using 需要
原文地址:https://www.cnblogs.com/chenxingyang/p/9747930.html
评论