geekbrains_network_programming/lesson_03/source/client.cpp

51 lines
1.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* client.cpp
*
* Created on: 7 сент. 2022 г.
* Author: alexander
*/
#include <client.hpp>
#include <iostream>
#include <arpa/inet.h>
#include <unistd.h>
namespace zh
{
ClientTCP::ClientTCP(const std::string &address, const unsigned short int port, const unsigned short int sizeBuffer) : Server(port, sizeBuffer), _connect(false), _connfd(-1)
{
_socket = std::make_unique<Socket>(AF_INET, SOCK_STREAM, IPPROTO_IP);
_address = std::make_unique<Address>(AF_INET, address, port);
}
void ClientTCP::connect()
{
if (_connect)
{
std::cerr << "Клиентский сокет уже подключён к серверному сокету!" << std::endl;
return;
}
if (::connect((*_socket), reinterpret_cast<const sockaddr*>(&(*_address)), (*_address).size()) != 0)
std::cerr << "Не удаётся подключить клиентский сокет к серверному сокету!" << std::endl;
else
_connect = true;
chat();
}
void ClientTCP::chat()
{
while (_connect)
{
Buffer *bf = &(*_buffer);
bf->clear();
std::cin.getline(reinterpret_cast<char*>(bf->operator void *()), bf->getSize());
write(_connfd, *bf, bf->getSize());
}
close(*_socket);
}
}