udp使用的是数据报传输。可以一对一,一对多进行传输,用于快速,实时性高的场景
服务器端:
使用步骤:
1.创建socket
2.bind绑定可接收的客户端
3.while{
recv接收数据
send发送数据
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main()
{
// 创建socket
int cfd = socket(AF_INET, SOCK_DGRAM, 0);
if (cfd < 0)
{
perror("socket error");
return -1;
}
// 绑定
struct sockaddr_in serv;
struct sockaddr_in clientsock;
bzero(&serv, sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_port = htons(9999);
serv.sin_addr.s_addr = htonl(INADDR_ANY);
bind(cfd, (struct sockaddr *)&serv, sizeof(serv));
int i;
int n;
socklen_t len;
char buf[1024];
while (1)
{
// 读取数据
memset(buf, 0x00, sizeof(buf));
len = sizeof(clientsock);
n = recvfrom(cfd, buf, sizeof(buf), 0, (struct sockaddr *)&clientsock, &len);
// 将大写转换为小写
for (i = 0; i < n; i++)
{
buf[i] = toupper(buf[i]);
}
char sIP[16];
memset(sIP, 0x00, sizeof(sIP));
printf("ip:[%s] port:[%d] n:[%d], buf:[%s]\n", inet_ntop(AF_INET, &clientsock.sin_addr.s_addr, sIP, sizeof(sIP)), ntohs(clientsock.sin_port), n, buf);
// 发送数据
sendto(cfd, buf, n, 0, (struct sockaddr *)&clientsock, len);
}
// 关闭套接字
close(cfd);
return 0;
}
客户端:
使用步骤:
1.创建socket
2.while{
send发送数据
接受数据
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main()
{
//创建socket
int cfd = socket(AF_INET, SOCK_DGRAM, 0);
if(cfd<0)
{
perror("socket error");
return -1;
}
int n;
char buf[1024];
struct sockaddr_in serv;
serv.sin_family = AF_INET;
serv.sin_port = htons(9999);
inet_pton(AF_INET, "192.168.3.99", &serv.sin_addr.s_addr);
while(1)
{
//读标准输入数据
memset(buf, 0x00, sizeof(buf));
n = read(STDIN_FILENO, buf, sizeof(buf));
//发送数据
sendto(cfd, buf, n, 0, (struct sockaddr *)&serv, sizeof(serv));
//读取数据
memset(buf, 0x00, sizeof(buf));
n = recvfrom(cfd, buf, sizeof(buf), 0, NULL, NULL);
printf("n:[%d], buf:[%s]\n", n, buf);
}
//关闭套接字
close(cfd);
return 0;
}