Reputation: 817
I'm trying to embed a telnet server in a data-capture program I've written. I've got both the data capture, and the telnet server working in their own classes, but now I want to transfer data from one to another, and I'm not sure where to start.
In the example below, I want to be able to send a command to the telnet server to request a data packet from the data capture thread.
So, in code (C++) this is what I want to do:
#include <thread>
void StartTelnetServer()
{
MyTelnetClass tnet;
tnet.Start(); // In here, server starts listening for connections.
}
void StartDataCapture()
{
MyDataCapture dCap;
dCap.Start(); // In here, data capture begins
}
main()
{
std::thread tnetThread(StartTelnetServer);
std::thread dCapThread(StartDataCapture);
// This will run until killed
}
I then want to telnet into it, with a string command such as "SIZE" and for the telnet class to query the latest dCap.GetSize(). There are dozen or so bits of data that I'll want to access in this way. Do I need to declare a static structure of some sort that both classes access? Am I way off base?!
This needs to run on Linux, if that matters to anything.
Upvotes: 0
Views: 75
Reputation: 409442
If the telnet handler should be able to access the data-capture object, but not the other way around, you can create both object in the main
function, passing the data-capture object by reference to the telnet handler constructor. Then start the threads using the Start
member functions instead.
Something like
...
class MyDataCapture;
class MyTelnetClass
{
public:
MyTelnetClass(MyDataCapture& dc)
: dCap(dc)
{}
...
private:
MyDataCapture& dCap;
...
};
...
int main()
{
MyDataCapture dCap;
MyTelnetClass tnet{dCap}
std::thread dCapThread(&MyDataCapture::Start, dCap);
std::thread tnetThread(&MyTelnetClass::Start, tnet);
...
}
This way the telnet handler can just call functions in the data-capture object when needed. Be careful through so you don't get data-races, protect data with mutexes and locks.
If you want the data-capture object to call functions in the telnet handler object as well you can't use references but have to use pointers.
Upvotes: 3