PDA

View Full Version : Read text lines using QDataStream or QTextStream or neither from tcpsocket?



ocgltd
27th September 2013, 23:00
I am creating a simple TCP server, and have a slot/function built which reads incoming text from a client (telnet connection) on a TCP socket. I've used the Fortune code examples to help me, but had to remove QDataStream since it didn't work as expected.

I want my readCommand function to collected incoming characters from a telnet client connection, and once it finds a newline or return to remove the typed command from the input buffer, remove /n and /r, add it to my string list (commandList), and then echo the commands (seperate function). Here's what I've got so far:


void MyServer::readCommand()
{
inBuffer += tcpSocketPtr->readAll();

// While newline is present, extract the command
int nextNewlinePos;
while ((nextNewlinePos = inBuffer.indexOf('\n')) > -1) {
commandList << inBuffer.left(nextNewlinePos);
inBuffer.remove(0,nextNewlinePos);
// Get rid of /n /r if present somehow
}
if (commandList.size() > 0)
{
echoCommand();
}
}

Before I start stripping /n and /r etc. manually, my gut is telling me there is a better way to do this. Is QTextStream the way to go? Can someone provide a simple(r) alternative to what I am trying to achieve? Note that QTextStream's readline won't work since it will return the contents of inbuffer in the case that there is NO newline, or the max string length is reached. I somehow need to test for newlines still...

anda_skoa
28th September 2013, 10:02
Have a look at QIODevice::canReadLine()

I would go for a QBuffer that always gets the available data from the socket (clearing network buffers as soon as possible) and is then used as the IO device for the text stream.

Cheers,
_