geekbrains_network_programming/lesson_01/headers/client.h

68 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.h
*
* Created on: 10 авг. 2022 г.
* Author: alexander
*/
#pragma once
#include <socket.h>
#include <address.h>
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#define MAXLINE 1024
namespace azh
{
class Client
{
private:
Socket _socket;
Address _address;
char _buffer[MAXLINE];
long int _recv_len;
public:
Client(Socket &socket, Address &address) :
_socket(socket), _address(address), _recv_len(0)
{
}
Client() :
_recv_len(0)
{
}
void createUDP(unsigned short int port)
{
_socket = { AF_INET, SOCK_DGRAM, IPPROTO_UDP };
_address = { AF_INET, INADDR_ANY, port };
}
void start()
{
while (true)
{
char message[MAXLINE];
message[MAXLINE] = '\0';
std::cin.getline(message, MAXLINE);
sendto(_socket, message, strlen(message), MSG_CONFIRM, reinterpret_cast<const sockaddr*>(&_address), _address.size());
_recv_len = recvfrom(_socket, _buffer, MAXLINE - 1, MSG_WAITALL, reinterpret_cast<sockaddr*>(&_address), &_address.size());
if (_recv_len > 0)
{
_buffer[_recv_len] = '\0';
std::cout << _buffer << std::endl;
}
}
}
};
}