Exemple #1
0
void
mainLoop(QSocketDevice& socket, bool debug)
{
    CommandProcessor processor;
    QString data;

    bool done = false;
    while (!done) {
	int timeout = -1;
	if (processor.waitingForResults())
	    timeout = 50;
	// TODO: different timeout if using POS and not ping

	bool wasTimeout = false;
	int result = socket.waitForMore(timeout, &wasTimeout);
	if (socket.atEnd() && result == 0 && !wasTimeout)
	    break;

	if (result == -1) {
	    logError("waitForMore error: %d", errno);
	    break;
	}

	if (processor.waitingForResults() && processor.resultsAvailable()) {
	    QString type;
	    QStringList results;
	    processor.getResults(type, results);
	    send(socket, type, results, debug);
	}

	if (wasTimeout) continue;

	char buffer[result + 1];
	result = socket.readBlock(buffer, result);
	if (result == -1) {
	    logError("readBlock error: %d", errno);
	    break;
	}

	buffer[result] = 0;
	data += QString::fromUtf8(buffer);

	while (true) {
	    QString line;
	    if (data.left(1) == "\002") {
		int index = data.find('\003');
		if (index == -1) break;

		line = data.mid(1, index - 1);
		data = data.mid(index + 1);
	    } else {
		int index = data.find('\n');
		if (index == -1) break;

		line = data.left(index);
		data = data.mid(index + 1);

		while (line.right(1) == "\r")
		    line = line.left(line.length() - 1);
	    }

	    if (line.isEmpty()) continue;
	    if (debug) logDebug("recv: " + line);

	    if (line == "ping") {
		send(socket, "ping:", "pong", debug);
	    } else if (line == "quit" || line == "exit") {
		done = true;
	    } else {
		processor.processCommand(line);
		if (processor.resultsAvailable()) {
		    QString type;
		    QStringList results;
		    processor.getResults(type, results);
		    send(socket, type, results, debug);
		}
	    }
	}
    }
}