Ai
1 Star 0 Fork 0

Shawy/2023Linux

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
UdpClient.hpp 2.35 KB
一键复制 编辑 原始数据 按行查看 历史
Shawy 提交于 2023-04-30 23:14 +08:00 . command version UdpServer
#pragma once
#include <iostream>
#include <string>
#include "Log.hpp"
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SIZE 1024
class UdpClient
{
public:
UdpClient(uint16_t port, std::string ip = "")
: _ip(ip)
, _port(port)
, _sockfd(-1)
{}
~UdpClient()
{
if (_sockfd >= 0) close(_sockfd);
}
bool initClient()
{
// 1. 创建套接字
_sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (_sockfd < 0)
{
logMessage(FATAL, "%d:%s", errno, strerror(errno));
exit(2);
}
logMessage(DEBUG, "%s: %d", "create socket success, sockfd", _sockfd);
// 2. bind (由OS完成)
return true;
}
void Start()
{
// 3. 发送数据
struct sockaddr_in server; // 创建数据包
memset(&server, 0, sizeof(server)); // 初始化为0
server.sin_family = AF_INET; // 指定通信协议
server.sin_addr.s_addr = inet_addr(_ip.c_str()); // 将点分十进制的IP字符串转化为二进制的网络字节序
server.sin_port = htons(_port); // 主机字节序->网络字节序
std::string message;
char buffer[SIZE];
while (1)
{
std::cout << "请输入信息# ";
std::getline(std::cin, message); // 输入数据
if (message == "quit")
break;
// 3.1 发送数据
sendto(_sockfd, message.c_str(), message.size(), 0,
(struct sockaddr *)&server, sizeof(server));
// 4. 处理服务器返回的响应数据
// 4.1 定义一个临时结构体
struct sockaddr_in tmp;
socklen_t len = sizeof(tmp);
ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer), 0,
(struct sockaddr *)&tmp, &len);
if (s > 0) // 读取成功
{
buffer[s] = 0;
std::cout << "server echo# " << buffer << std::endl;
}
// else 省略差错处理
}
}
private:
uint16_t _port; // 端口号
std::string _ip; // IP地址
int _sockfd; // 套接字文件描述符
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/shawyxy/2023-linux.git
git@gitee.com:shawyxy/2023-linux.git
shawyxy
2023-linux
2023Linux
main

搜索帮助