1.UDP通信
①UDP通信流程
②UDP相关函数使用介绍
#include
#include
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen);
- 参数:
- sockfd : 通信的fd
- buf : 要发送的数据
- len : 发送数据的长度
- flags : 0
- dest_addr : 通信的另外一端的地址信息
- addrlen : 地址的内存大小
- 返回值:
- -1:失败,出现错误
- >0:实际发送的字节数
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags, struct
sockaddr *src_addr, socklen_t *addrlen);
- 参数:
- sockfd : 通信的fd
- buf : 接收数据的数组
- len : 数组的大小
- flags : 0
- src_addr : 用来保存另外一端的地址信息,不需要可以指定为NULL
- addrlen : 地址的内存大小
- 返回值:
- >0: 实际收到的字节数
- 0:对方关闭了读端
- -1:失败
2.UDP代码实现
①服务端
#include
#include
#include
#include
using namespace std;
int main() {
int client_fd = socket(PF_INET, SOCK_DGRAM, 0);
if (client_fd == -1) {
perror("-1");
exit(-1);
}
sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8888);
server_addr.sin_addr.s_addr = INADDR_ANY;
int bind_ret = bind(client_fd, (sockaddr *)&server_addr, sizeof(server_addr));
if (bind_ret == -1) {
perror("bind");
exit(-1);
}
char recvBuf[128];
while (1) {
sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int recv_ret = recvfrom(client_fd, recvBuf, sizeof(recvBuf), 0, (sockaddr *)&client_addr, &client_addr_len);
if (recv_ret == -1) {
perror("recvfrom");
exit(-1);
} else if (recv_ret == 0) {
cout << "client closed..." << endl;
continue;
}
char client_ip[16];
inet_ntop(AF_INET, (sockaddr *)&client_addr.sin_addr.s_addr, client_ip, sizeof(client_ip));
printf("client ip: %s, client port: %d\n", client_ip, ntohs(client_addr.sin_port));
printf("I am server, data: %s\n", recvBuf);
sendto(client_fd, recvBuf, sizeof(recvBuf), 0, (sockaddr *)&client_addr, sizeof(server_addr));
}
close(client_fd);
return 0;
}
②客户端
#include
#include
#include
#include
using namespace std;
int main() {
int server_fd = socket(PF_INET, SOCK_DGRAM, 0);
if (server_fd == -1) {
perror("socket");
exit(-1);
}
sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
inet_pton(AF_INET, "192.168.246.130", &server_addr.sin_addr.s_addr);
server_addr.sin_port = htons(8888);
char sendBuf[128];
int num = 0;
while (1) {
sprintf(sendBuf, "hello server, num: %d\n", num ++ );
sendto(server_fd, sendBuf, strlen(sendBuf) + 1, 0, (sockaddr *)&server_addr, sizeof(server_addr));
int recv_ret = recvfrom(server_fd, sendBuf, sizeof(sendBuf), 0, NULL, NULL);
if (recv_ret == -1) {
perror("recvfrom");
exit(-1);
} else if (recv_ret == 0) {
cout << "server closed..." << endl;
continue;
}
printf("I am client, data: %s\n", sendBuf);
sleep(1);
}
close(server_fd);
return 0;
}