Skip to content
UDP_Protocol.h 1.55 KiB
Newer Older
Valerio Pastore's avatar
Valerio Pastore committed
/*
 *
 *  Created on: Mar 1, 2021
 *      Author: astrisw
 */
astri's avatar
astri committed
#pragma once
Valerio Pastore's avatar
Valerio Pastore committed

#include <Base_Protocol.h>
astri's avatar
astri committed
#include <Base_Configurator.h>
Valerio Pastore's avatar
Valerio Pastore committed

/*
Valerio Pastore's avatar
Valerio Pastore committed
 * class UDPProtocol
Valerio Pastore's avatar
Valerio Pastore committed
 * Implementation of a UDP socket
 * @member field fd_sock: socket file descriptor
 * @member field sockaddr_in: struct of the client address.
 */
astri's avatar
astri committed
namespace inaf::oasbo::ConnectionProtocols {
Valerio Pastore's avatar
Valerio Pastore committed

astri's avatar
astri committed
class UDPProtocol: public BaseProtocol {
Valerio Pastore's avatar
Valerio Pastore committed
protected:
	int srv_sock;
	int cli_sock;
astri's avatar
astri committed

Valerio Pastore's avatar
Valerio Pastore committed
	struct sockaddr_in cliaddr;
	struct sockaddr_in srvaddr;
astri's avatar
astri committed
	void split_ip_port(const std::string &ip_port, std::string &ip,
			std::string &port);
	int receiveAtLeastHeaderSizeBytes(uint8_t *buff, int headerSize,
			int packetSize);
	void resetPacket(PacketLib::BasePacket&, int bytes);
	UDPProtocol(std::string ip, int prt);
	UDPProtocol();

astri's avatar
astri committed
public:
astri's avatar
astri committed
	std::string ip { };
astri's avatar
astri committed
	int port;

	~UDPProtocol();

	int connectToServer() override;
	int connectToClient() override;
	int closeConnectionToServer() override;
	int closeConnectionToClient() override;
	bool isConnectedToClient() const override;
	bool isConnectedToServer() const override;
astri's avatar
astri committed
	int receiveFromClient(PacketLib::BasePacket&) override;
	int sendToServer(PacketLib::BasePacket&) override;

	friend class Builder;
	class Builder {
	protected:
		UDPProtocol *protocol;
	public:
		std::string ip_key { "ip" };
		std::string port_key { "port" };

		Builder();
		Builder(std::string ip, int port);
		~Builder();

		void reset();

		Builder* configFrom(Configurators::BaseConfigurator *conf);

		Builder* setIp(std::string ip);

		Builder* setPort(int port);
astri's avatar
astri committed

astri's avatar
astri committed
		UDPProtocol* getProtocol();
	};
astri's avatar
astri committed