I need help on constructing the endpoint with 3 arguements. Currently "IP Address" & "Port" are there in the constructor. But i need to include an integer arguement to identify the connection. Ideally as mentioned below.
asio::ip::tcp::endpoint endpoint(asio::ip::make_address("127.0.0.1", ec), 7497, clientId = 0);
Could you please help whether i have to modify the base class or can i inherit the base class & add this arguement? if inheriting is easy, please guide me on that.
int main(int argc)
{
int clientId = 0;
asio::error_code ec;
// Create a "context" - essentially the platform specific interface
asio::io_context context;
// Get th addres of somewhere w wish to connect to
asio::ip::tcp::endpoint endpoint(asio::ip::make_address("127.0.0.1", ec), 7497);
// Create a socket, the context will deliver the implementation
asio::ip::tcp::socket socket(context);
// tell socket to try and connect
socket.connect(endpoint, ec);
if (!ec)
{
std::cout << "Conected!" << std::endl;
}
else
{
std::cout << "Failed to connect to address:\n" << ec.message() << std::endl;
}
if (socket.is_open())
system("pause");
return 0;
}
Inherited class:
#pragma once
#include <iostream>
#ifdef _WIN32
#define _WIN32_WINNT 0x0A00
#endif
#define ASIO_STANDALONE
#include <asio.hpp>
#include <asio/ts/buffer.hpp>
#include <asio/ts/internet.hpp>
// Get th addres of somewhere w wish to connect to
class clien : public asio::ip::tcp::endpoint, asio::ip::address
{
public:
typedef asio::ip::tcp::endpoint endpoint;
char asio::ip::address;
int clientId;
//clien(int cid);
clien(str ep, int p, int cid) : asio::ip::tcp::endpoint(ep), char asio::ip::address, int cid;
{
clientId = cid;
}
};
CodePudding user response:
since the class overloading way look to be the easiest:
class clien : public asio::ip::tcp::endpoint {
// inherit endpoint (because it the class you want to change)
protected:
int __cid; // the id
public:
int clientId() const { return __cid; } // getter
void clientId(int cid) { __cid = cid; } // setter
clien(str ep, int p, int cid) :
asio::ip::tcp::endpoint(ep, p), // construct the actual endpoint
__cid(cid){} // set the cid
};
i'm not familiar with the library so some type (for the constructor) might be wrong.
CodePudding user response:
You can make a new type using endpoint and id
struct MyEndpoint{
asio::ip::tcp::endpoint endpoint{};
int someId{};
}
Create the endpoint
auto const someId = 42;
auto myEndpoint = MyEndpoint{ .endpoint = { boost::asio::ip::tcp::v4 (), 7497 }, .someId = someId };
Now you can get the id and the endpoint
myEndpoint.someId; // To get the id
myEndpoint.endpoint; // To get the endpoint
Another idea is to make a pair of id and endpoint
auto const someId=42;
auto idAndEndpoint= std::make_pair(someId, asio::ip::tcp::endpoint{(asio::ip::make_address("127.0.0.1", ec), 7497)});
Now you can get the id and the endpoint
auto &[id, endpoint] = idAndEndpoint;