UDP(User Datagram Protocol)用户数据报协议是一种非面向连接的协议,这种协议并不能保证我们的网络程序的连接是可靠的,可能出现丢包现象,在视频传输时用的就是UDP协议,传输可能会出现花屏现象,但尽可能保证传输的流畅度
基本调用和TCP类似,
接收要使用recvfrom
发送可以使用sendto或connect + recvfreom
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen);
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen);
例程:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define BACKLOG 10
#define SERVER_PORT 8888
int main(int argc,char **argv)
{
int iServerFd, iClientFd;
int iRet;
struct sockaddr_in tSocketServerAddr;
struct sockaddr_in tSocketClientAddr;
int iAddrLen = sizeof(struct sockaddr);
char pcBuf[1024];
int iLen;
iServerFd = socket(AF_INET, SOCK_DGRAM, 0);
if(iServerFd < 0)
{
printf("socket error\r\n");
return -1;
}
tSocketServerAddr.sin_family = AF_INET;
tSocketServerAddr.sin_port = htons(SERVER_PORT);
tSocketServerAddr.sin_addr.s_addr = INADDR_ANY;
memset(tSocketServerAddr.sin_zero, 0, 8);
iRet = bind(iServerFd, (struct sockaddr *)&tSocketServerAddr, iAddrLen);
if(iRet < 0)
{
printf("bind error\r\n");
goto error;
}
while(1)
{
iAddrLen = sizeof(struct sockaddr);
iLen = recvfrom(iServerFd, pcBuf, 1023, 0, (struct sockaddr *)&tSocketClientAddr, &iAddrLen);
if(iLen > 0)
{
pcBuf[iLen] = '\0';
printf("get msg %s from Client %s\r\n", pcBuf, inet_ntoa(tSocketClientAddr.sin_addr));
}
}
close(iServerFd);
return 0;
error:
close(iServerFd);
return -1;
}
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVER_PORT 8888
int main(int argc,char **argv)
{
int iServerFd, iClientFd;
int iRet;
struct sockaddr_in tSocketServerAddr;
char pcBuf[1024];
int iLen;
int i;
if(argc != 2)
{
printf("Usage : %s \r\n", argv[0]);
return -1;
}
iClientFd = socket(AF_INET, SOCK_DGRAM, 0);
if(iClientFd < 0)
{
printf("socket error\r\n");
return -1;
}
tSocketServerAddr.sin_family = AF_INET;
tSocketServerAddr.sin_port = htons(SERVER_PORT);
if(!inet_aton(argv[1], &tSocketServerAddr.sin_addr))
{
printf("ivalid server_ip\r\n");
goto error;
}
memset(tSocketServerAddr.sin_zero, 0, 8);
#ifdef OR
iRet = connect(iClientFd, (struct sockaddr *)&tSocketServerAddr, sizeof(struct sockaddr));
if(iRet < 0)
{
printf("connect error\r\n");
return -1;
}
#endif
while(1)
{
if(!fgets(pcBuf, 1023, stdin))
{
printf("fgets error\r\n");
goto error;
}
#ifdef OR
iLen = send(iClientFd, pcBuf, strlen(pcBuf), 0);
#else
i = sizeof(struct sockaddr);
iLen = sendto(iClientFd, pcBuf, strlen(pcBuf), 0, (struct sockaddr *)&tSocketServerAddr, i);
#endif
if(iLen <= 0)
{
printf("send error\r\n");
goto error;
}
}
close(iClientFd);
return 0;
error:
close(iClientFd);
return -1;
}