PDA

View Full Version : Write contents of std::stringstream to a socket (or connect them)



nomiz
29th September 2011, 15:56
Dear all,

I have a question on using a std::stringstream to write to a QTcpSocket, so the contents will be transfered over the network connection.

I have a parent object:
A QObject with a private QTcpSocket attribute called socket.

When socket sends it readyRead() signal to parent, the parent creates a child (a QObject and QRunnable) and starts running its run();

Due to an API implementation, the child produces an std::stringstream output, which is the output of some calculation.

What could I do to take output (or contents of output) from child and give it to the parent, so parent can write its contents to the socket? Or maybe if connect socket->write() with output?

Thank you in advance for any hints!

Cheers

nomiz
30th September 2011, 16:49
Ok, that was easier then thought:
Apparently dup2() (never heard of it..) can redirect stdout and stderr to another (file or socket)descriptor (sorry, never heard of that either... :p ).

Whenever the QTcpServer gets an incoming connection, a incomingConnection(int handle) is emitted. This handle can be used in order to redirect all stdout ans stderr over a newly created socket.


void Server::incomingConnection(int handle)
{
Client *client = new Client(this);
client->setSocket(handle);
}

In client:


void Client::setSocket(int descriptor)
{
socket = new QTcpSocket(this);
socket->setSocketDescriptor(descriptor);

dup2(descriptor, 1); // stdout
dup2(descriptor, 2); // stderr

qDebug() << "This text ends up at the telnet-session of the connected client";

// connect socket signals to slots
connect(socket, SIGNAL(connected()), this, SLOT(socketConnected()));
connect(socket, SIGNAL(readyRead()), this, SLOT(socketReadyRead()));

qDebug() << "Socket created";
}