Ai
1 Star 0 Fork 0

Shawy/2023Linux

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
TcpClient.hpp 3.10 KB
一键复制 编辑 原始数据 按行查看 历史
Shawy 提交于 2023-05-14 22:19 +08:00 . ThreadPool version TcpServer
#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Log.hpp"
#define SIZE 1024
class TcpClient
{
public:
TcpClient(uint16_t port, std::string ip = "")
: _port(port), _ip(ip), _sockfd(-1)
{
}
~TcpClient()
{
if (_sockfd >= 0)
close(_sockfd);
}
bool initClient()
{
// 1. 创建套接字
_sockfd = socket(AF_INET, SOCK_STREAM, 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. 连接
// 3.1 填充服务端信息 本地->网络
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(_ip.c_str());
server.sin_port = htons(_port);
// 3.2 连接
if (connect(_sockfd, (sockaddr *)&server, sizeof(server)) < 0) // 连接失败
{
logMessage(FATAL, "connect()errno:%d:%s", errno, strerror(errno));
exit(3);
}
logMessage(DEBUG, "start TcpClient...%s", strerror(errno)); // 连接成功
// 4.0 发送并接收数据
while (1)
{
// 4.1 从标准输入流获取数据
std::string message;
std::cout << "请输入>>> ";
std::getline(std::cin, message);
if (message == "quit")
break;
else if(message.empty()) // 只按下回车不输入数据
continue;
// 4.2 发送数据
ssize_t s = send(_sockfd, message.c_str(), message.size(), 0);
if (s > 0) // 发送成功
{
char buffer[SIZE];
// 4.3 接收服务器返回的数据
ssize_t s = recv(_sockfd, buffer, sizeof(buffer), 0);
if (s > 0) // 接收成功
{
buffer[s] = '\0'; // 标记数据的末尾
std::cout << "TcpServer回显# " << buffer << std::endl;
}
else if (s == 0) // 读取到0个字节的数据
{
logMessage(NORMAL, "TcpServer: IP[%s], PORT[%u] shut down...me too", _ip.c_str(), _port);
close(_sockfd);
break;
}
else // 读取失败
{
logMessage(ERROR, "recv()errno:%d:%s", errno, strerror(errno));
close(_sockfd);
break;
}
}
else // 发送0个字节的数据或失败
{
logMessage(ERROR, "send()errno:%d:%s", errno, strerror(errno));
close(_sockfd);
break;
}
}
}
private:
int _sockfd;
uint16_t _port;
std::string _ip;
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/shawyxy/2023-linux.git
git@gitee.com:shawyxy/2023-linux.git
shawyxy
2023-linux
2023Linux
main

搜索帮助