本文整理汇总了C++中QTcpSocket::readLine方法的典型用法代码示例。如果您正苦于以下问题:C++ QTcpSocket::readLine方法的具体用法?C++ QTcpSocket::readLine怎么用?C++ QTcpSocket::readLine使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QTcpSocket
的用法示例。
在下文中一共展示了QTcpSocket::readLine方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: onSocketReadyRead
void KCToolServer::onSocketReadyRead()
{
QTcpSocket *socket = qobject_cast<QTcpSocket*>(QObject::sender());
// Parse the first line
if(!socket->property("firstLineRead").toBool())
{
QString line(socket->readLine());
int sepPos1(line.indexOf(" "));
int sepPos2(line.indexOf(" ", sepPos1+1));
QString method(line.left(sepPos1));
QString path(line.mid(sepPos1+1, sepPos2 - sepPos1 - 1));
socket->setProperty("method", method);
socket->setProperty("path", path);
socket->setProperty("firstLineRead", true);
}
// Parse Headers!
if(!socket->property("headerRead").toBool()) {
QVariantMap headers(socket->property("headers").toMap());
while(socket->canReadLine()) {
QString line = QString(socket->readLine()).trimmed();
// The header section is terminated by an empty line
if(line == "") {
socket->setProperty("headerRead", true);
break;
}
// Split it up
int sepPos(line.indexOf(":"));
QString key(line.left(sepPos).trimmed());
QString val(line.mid(sepPos+1).trimmed());
headers.insertMulti(key, val);
}
socket->setProperty("headers", headers);
}
qint64 contentLength = socket->property("headers").toMap().value("Content-Length").toLongLong();
// Read the body into a buffer
if(socket->bytesAvailable()) {
QByteArray buffer(socket->property("buffer").toByteArray());
qint64 toRead = contentLength - buffer.size();
buffer.append(socket->read(toRead));
socket->setProperty("buffer", buffer);
socket->setProperty("toRead", contentLength - buffer.size());
// If we have a Content-Length (toLong() fails with 0)
if(contentLength > 0 && buffer.size() >= contentLength)
this->handleRequest(socket);
} else if(contentLength == -1 || contentLength == 0) {
this->handleRequest(socket);
}
}
示例2: readClient
void HttpServer::readClient()
{
if (!m_accept)
return;
QTcpSocket* socket = (QTcpSocket*)sender();
try
{
if (socket->canReadLine())
{
QString hdr = QString(socket->readLine());
QVariantMap headers;
if (hdr.startsWith("POST") || hdr.startsWith("GET"))
{
QUrl url(hdr.split(' ')[1]);
QString l;
do
{
l = socket->readLine();
//collect headers
int colon = l.indexOf(':');
if (colon > 0)
headers[l.left(colon).trimmed().toLower()] = l.right(l.length() - colon - 1).trimmed();
}
while (!(l.isEmpty() || l == "\r" || l == "\r\n"));
QString content = socket->readAll();
std::unique_ptr<HttpRequest> request(new HttpRequest(this, std::move(url), std::move(content), std::move(headers)));
clientConnected(request.get());
QTextStream os(socket);
os.setAutoDetectUnicode(true);
QString q;
///@todo: allow setting response content-type, charset, etc
os << "HTTP/1.0 200 Ok\r\n";
if (!request->m_responseContentType.isEmpty())
os << "Content-Type: " << request->m_responseContentType << "; ";
os << "charset=\"utf-8\"\r\n\r\n";
os << request->m_response;
}
}
}
catch(...)
{
delete socket;
throw;
}
socket->close();
if (socket->state() == QTcpSocket::UnconnectedState)
delete socket;
}
示例3: readClient
void HttpDaemon::readClient()
{
QTcpSocket* socket = (QTcpSocket*)sender();
if (socket->canReadLine())
{
QTextStream os(socket);
os.setAutoDetectUnicode(true);
os << "HTTP/1.0 200 Ok\r\n"
"Content-Type: text/html; charset=\"utf-8\"\r\n"
"\r\n";
QStringList tokens = QString(socket->readLine()).split(QRegExp("[ \r\n][ \r\n]*"));
QRegExp pathPattern("^/websocket\\.(html|js)$");
if (pathPattern.exactMatch(tokens[1]))
{
QFile file (":" + pathPattern.capturedTexts()[0]);
file.open(QFile::ReadOnly);
os << file.readAll()
<< "\n\n";
}
else
{
os << "<h1>Nothing to see here</h1>\n\n";
}
socket->close();
if (socket->state() == QTcpSocket::UnconnectedState)
delete socket;
}
}
示例4: run
void ClientThread::run()
{
QTcpSocket tcpSocket;
if (!tcpSocket.setSocketDescriptor(m_socketDescriptor)) {
qWarning() << ":(((";
emit error(tcpSocket.error());
return;
}
m_running = true;
QString command, response;
// Send greetings
tcpSocket.write("OK MPD 0.12.2\n");
while (m_running && (tcpSocket.state() == QAbstractSocket::ConnectedState)) {
m_running = tcpSocket.waitForReadyRead(); // Wait for command,
// if none is received until timeout
// (default 30 seconds, stop running).
command = QString(tcpSocket.readLine()).trimmed();
qDebug() << command;
tcpSocket.write(parseCommand(command).toLocal8Bit());
}
tcpSocket.disconnectFromHost();
}
示例5: sendResponse
void Server::sendResponse() {
QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));
stringstream peerStream;
peerStream << clientConnection->peerAddress().toString().toStdString()
<< ":"
<< clientConnection->peerPort();
string peer = peerStream.str();
if (clientConnection->waitForReadyRead(10000)) {
clientConnection->readLine(readBuffer, BUFFER_LEN);
string message(readBuffer);
string deviceId = "";
if (message.length() > 4) {
deviceId = message.substr(4);
}
if (message.find("GET ", 0, 4) == 0) {
string response = processGetOpertion(peer, deviceId);
clientConnection->write(response.c_str());
} else if (message.find("ADD ", 0, 4) == 0) {
bool added = processAddOpertion(deviceId);
if (added) {
clientConnection->write("ADDED");
} else {
clientConnection->write("NOT ADDED");
}
}
}
clientConnection->disconnectFromHost();
}
示例6: readClient
void Client::readClient() {
//qDebug()<<"Client::readClient";
QTcpSocket* socket = (QTcpSocket*)sender();
QByteArray buffer=socket->readLine();
QString response=parseCommand(QString(buffer));
socket->write(response.toLatin1());
}
示例7: nachrichtEmpfangen
void Server::nachrichtEmpfangen() {
QTcpSocket *client = dynamic_cast<QTcpSocket *>(sender());
if (client == 0) {
std::cerr << "Server::nachrichtEmpfangen : sender() ist nicht QTcpSocket";
}
while (client->canReadLine()) {
QByteArray nachricht_bytes = client->readLine();
QString nachricht = QString::fromUtf8(nachricht_bytes);
QString typ = nachricht.section(QString::fromLatin1("\x1F"),0,0);
if (typ == QString::fromLatin1("chat")) {
for (int i = 0; i < anzahlClients; ++i) {
if (clients[i] != client) {
clients[i]->write(nachricht_bytes);
}
}
QString absender = nachricht.section(QString::fromLatin1("\x1F"),1,1);
QString text = nachricht.section(QString::fromLatin1("\x1F"),2,-1);
emit chatEmpfangen(QString::fromLatin1("<b>") + absender + QString::fromLatin1("</b>: ") + text);
} else if (typ == QString::fromLatin1("wurf")) {
for (int i = 0; i < anzahlClients; ++i) {
if (clients[i] != client) {
clients[i]->write(nachricht_bytes);
}
}
int augenzahl = nachricht.section(QString::fromLatin1("\x1F"),1,1).toInt();
emit wurfelnEmpfangen(augenzahl);
}
}
}
示例8: readyRead
/**
* Slot
* @brief Serveur::pretALire
*/
void Serveur::readyRead()
{
QTcpSocket *client = (QTcpSocket*)sender();
while(client->canReadLine())
{
QString ligne = QString::fromUtf8(client->readLine()).trimmed();
qDebug() << "Read line:" << ligne;
QRegExp meRegex("^/me:(.*)$");
if(meRegex.indexIn(ligne) != -1)
{
QString utilisateur = meRegex.cap(1);
m_utilisateurs[client] = utilisateur;
foreach(QTcpSocket *client, m_clients)
client->write(QString("Serveur:" + utilisateur + " a rejoint le serveur.\n").toUtf8());
envoyerListeUtilisateur();
}
else if(m_utilisateurs.contains(client))
{
QString message = ligne;
QString utilisateur = m_utilisateurs[client];
qDebug() << "Utilisateur:" << utilisateur;
qDebug() << "Message:" << message;
foreach(QTcpSocket *otherClient, m_clients)
otherClient->write(QString(utilisateur + ":" + message + "\n").toUtf8());
}
else
{
qWarning() << "Erreur du client:" << client->peerAddress().toString() << ligne;
}
}
}
示例9: readLine
static QByteArray readLine(QTcpSocket &sock)
{
while (!sock.canReadLine() && sock.waitForReadyRead());
if (sock.state() != QAbstractSocket::ConnectedState)
return QByteArray();
return sock.readLine();
}
示例10: os
void HttpServer :: readClient()
{
if (disabled) return;
QTcpSocket *socket = (QTcpSocket*)sender();
if( socket->canReadLine()) {
QString request = socket->readLine();
QStringList tokens = request.split(QRegExp("[ \r\n][ \r\n]*"));
if( tokens[0] == "GET") {
d->engine.globalObject().setProperty("token", tokens[1]);
QScriptValue reply = d->engine.evaluate("reply(token)");
QTextStream os(socket);
os.setAutoDetectUnicode(true);
os << reply.toString().toUtf8();
socket->close();
QtServiceBase::instance()->logMessage("Wrote index.html");
if(socket->state() == QTcpSocket::UnconnectedState) {
delete socket;
QtServiceBase::instance()->logMessage("Conncetion closed");
}
}
}
}
示例11: readyRead
void DataTransferServer::readyRead()
{
QTcpSocket *client = (QTcpSocket*)sender();
while(client->canReadLine()) {
QString message = QString::fromUtf8(client->readLine()).trimmed();
qDebug() << "Read line message:" << message;
foreach(QTcpSocket *otherClient, clients)
otherClient->write(QString(message + "\n").toUtf8());
}
}
示例12: readClient
void HttpDaemon :: readClient()
{
QTcpSocket *socket = (QTcpSocket*) sender();
if (socket->canReadLine()) {
QStringList tokens = QString(socket->readLine()).split(QRegExp("[ \r\n][ \r\n]*"));
handleToken(tokens, socket);
if (socket->state() == QTcpSocket::UnconnectedState) {
delete socket;
}
}
}
示例13: run
void ConnectionThread::run()
{
Debug() << "Thread started.";
QTcpSocket sock;
socketNoNagle(sockdescr);
if (!sock.setSocketDescriptor(sockdescr)) {
Error() << sock.errorString();
return;
}
QString remoteHostPort = sock.peerAddress().toString() + ":" + QString::number(sock.peerPort());
Log() << "Connection from peer " << remoteHostPort;
QString line;
forever {
if (sock.canReadLine() || sock.waitForReadyRead()) {
line = sock.readLine().trimmed();
while (StimApp::instance()->busy()) {
// special case case, stimapp is busy so keep polling with 1s intervals
Debug() << "StimApp busy, cannot process command right now.. trying again in 1 second";
sleep(1); // keep sleeping 1 second until the stimapp is no longer busy .. this keeps us from getting given commands while we are still initializing
}
// normal case case, stimapp not busy, proceed normally
QString resp;
resp = processLine(sock, line);
if (sock.state() != QAbstractSocket::ConnectedState) {
Debug() << "processLine() closed connection";
break;
}
if (!resp.isNull()) {
if (resp.length()) {
Debug() << "Sending: " << resp;
if (!resp.endsWith("\n")) resp += "\n";
QByteArray data(resp.toUtf8());
int len = sock.write(data);
if (len != data.length()) {
Debug() << "Sent " << len << " bytes but expected to send " << data.length() << " bytes!";
}
}
Debug() << "Sending: OK";
sock.write("OK\n");
} else {
Debug() << "Sending: ERROR";
sock.write("ERROR\n");
}
} else {
if (sock.error() != QAbstractSocket::SocketTimeoutError
|| sock.state() != QAbstractSocket::ConnectedState) {
Debug() << "Socket error: " << sock.error() << " Socket state: " << sock.state();
break;
}
}
}
Log() << "Connection ended (peer: " << remoteHostPort << ")";
Debug() << "Thread exiting.";
}
示例14: parser
void
LegacyPlayerListener::onDataReady()
{
QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
if (!socket) return;
connect( socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()) );
while (socket->canReadLine())
{
QString line = QString::fromUtf8( socket->readLine() );
try
{
PlayerCommandParser parser( line );
QString const id = parser.playerId();
PlayerConnection* connection = 0;
if (!m_connections.contains( id )) {
connection = m_connections[id] = new PlayerConnection( parser.playerId(), parser.playerName() );
emit newConnection( connection );
}
else
connection = m_connections[id];
switch (parser.command())
{
case CommandBootstrap:
qWarning() << "We no longer support Bootstrapping with the LegacyPlayerListener";
break;
case CommandTerm:
m_connections.remove( id );
// FALL THROUGH
default:
connection->handleCommand( parser.command(), parser.track() );
break;
}
socket->write( "OK\n" );
}
catch (std::invalid_argument& e)
{
QString const error = QString::fromUtf8( e.what() );
qWarning() << line << error;
QString s = "ERROR: " + error + "\n";
socket->write( s.toUtf8() );
}
}
socket->close();
}
示例15: readLine
QByteArray ImapPrivate::readLine (bool *ok) {
quint8 attempts = 0;
while (!socket->canReadLine() && attempts < 2) {
if (!socket->waitForReadyRead())
attempts++;
}
if (attempts >= 2) {
if (ok != NULL) *ok = false;
return(QByteArray());
}
if (ok != NULL) *ok = true;
#ifdef IMAP_DEBUG
QByteArray response = socket->readLine();
qDebug() << "readLine()" << response;
return(response);
#else
return(socket->readLine());
#endif
}