本文整理汇总了C++中QTcpSocket::canReadLine方法的典型用法代码示例。如果您正苦于以下问题:C++ QTcpSocket::canReadLine方法的具体用法?C++ QTcpSocket::canReadLine怎么用?C++ QTcpSocket::canReadLine使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QTcpSocket
的用法示例。
在下文中一共展示了QTcpSocket::canReadLine方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: 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);
}
}
}
示例2: readLine
static QByteArray readLine(QTcpSocket &sock)
{
while (!sock.canReadLine() && sock.waitForReadyRead());
if (sock.state() != QAbstractSocket::ConnectedState)
return QByteArray();
return sock.readLine();
}
示例3: 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");
}
}
}
}
示例4: 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;
}
}
示例5: 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;
}
}
}
示例6: 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);
}
}
示例7: 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());
}
}
示例8: 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();
}
示例9: 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;
}
}
}
示例10: 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.";
}
示例11: 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;
}
示例12: readClient
void HttpDaemon::readClient()
{
if (disabled)
return;
// This slot is called when the client sent data to the server. The
// server looks if it was a get request and sends a very simple HTML
// document back.
QTcpSocket* socket = (QTcpSocket*)sender();
if (socket->canReadLine()) {
QByteArray data = socket->readLine();
QStringList tokens = QString(data).split(QRegExp("[ \r\n][ \r\n]*"));
qDebug() << "incoming data" << tokens[1];
QUrl url("http://foo.bar" + tokens[1]);
QUrlQuery query(url);
qDebug() << "query is" << url.path();
if (url.path() == "/setstate") {
emit setState(StateTypeId(query.queryItems().first().first), QVariant(query.queryItems().first().second));
} else if (url.path() == "/generateevent") {
qDebug() << "got generateevent" << query.queryItemValue("eventtypeid");
emit triggerEvent(EventTypeId(query.queryItemValue("eventtypeid")));
} else if (url.path() == "/actionhistory") {
QTextStream os(socket);
os.setAutoDetectUnicode(true);
os << generateHeader();
for (int i = 0; i < m_actionList.count(); ++i) {
os << m_actionList.at(i).first.toString() << '\n';
}
socket->close();
return;
} else if (url.path() == "/clearactionhistory") {
m_actionList.clear();
}
if (tokens[0] == "GET") {
QTextStream os(socket);
os.setAutoDetectUnicode(true);
os << generateWebPage();
socket->close();
qDebug() << "Wrote to client";
if (socket->state() == QTcpSocket::UnconnectedState) {
delete socket;
qDebug() << "Connection closed";
}
}
}
}
示例13: dataRecieved
//The method checks for the data recieved and if a destroy command is recieved it echos out the command, if a score command is recieved it saves the score
//and if both scores have been recieved it sends out the winner.
void MultiplayerGUI::dataRecieved()
{
QTcpSocket * sock = dynamic_cast<QTcpSocket*>(sender());
while (sock->canReadLine()){
QString line = sock->readLine();
if (line.indexOf("DESTROY:") != -1){
for (QTcpSocket * socket: currentConnections){
if (socket != sock){
socket->write(line.toLocal8Bit());
}
}
}
else if (line.indexOf("SCORE:") != -1){
line = line.remove(0, 6);
QStringList scoreList = line.split(":");
if (player1Name == ""){
player1Name = scoreList.at(0);
player1Score = scoreList.at(1).toInt();
}
else{
player2Name = scoreList.at(0);
player2Score = scoreList.at(1).toInt();
if (player1Score > player2Score){
QString winningScore = "WINNER:" + player1Name + " wins with a score of " + QString::number(player1Score) +"\n";
for (QTcpSocket * sock: currentConnections){
sock->write(winningScore.toLocal8Bit());
}
}
else if (player1Score == player2Score){
QString winningScore = "WINNER: You have tied with a score of " + QString::number(player2Score) + "\n";
for (QTcpSocket * sock: currentConnections){
sock->write(winningScore.toLocal8Bit());
}
}
else{
QString winningScore = "WINNER:" + player2Name + " wins with a score of " + QString::number(player2Score) + "\n";
for (QTcpSocket * sock: currentConnections){
sock->write(winningScore.toLocal8Bit());
}
}
}
}
}
// ServerProcessThread * thread = new ServerProcessThread(sock, currentConnections);
//connect(thread, &QThread::finished, this, &MultiplayerGUI::serverProcessFinished);
//thread->start();
}
示例14: readClient
void EvopediaWebServer::readClient()
{
QTcpSocket* socket = (QTcpSocket*)sender();
if (!socket->canReadLine()) return;
/* TODO1 wait for end of request header? peek? */
const QList<QByteArray> tokens = socket->readLine().split(' ');
if (tokens[0] != "GET" || tokens.size() < 2) {
outputHeader(socket, "404");
closeConnection(socket);
return;
}
const QUrl url = QUrl::fromPercentEncoding(tokens[1]);
QString path = url.path();
if (path.endsWith("skins/common/images/magnify-clip.png"))
path = "/static/magnify-clip.png";
const QStringList pathParts = path.mid(1).split('/');
if (pathParts.length() < 1 || pathParts[0].isEmpty()) {
outputIndexPage(socket);
closeConnection(socket);
return;
}
const QString &firstPart = pathParts[0];
if (firstPart == "static") {
outputStatic(socket, pathParts);
} else if (firstPart == "search") {
outputSearchResult(socket, url.queryItemValue("q"), url.queryItemValue("lang"));
} else if (firstPart == "map") {
qreal lat = url.queryItemValue("lat").toDouble();
qreal lon = url.queryItemValue("lon").toDouble();
int zoom = url.queryItemValue("zoom").toInt();
mapViewRequested(lat, lon, zoom);
} else if (firstPart == "random") {
redirectRandom(socket, pathParts);
} else if (firstPart == "math" ||
(firstPart == "wiki" && pathParts.length() >= 2 && pathParts[1] == "math")) {
outputMathImage(socket, pathParts);
} else if (firstPart == "wiki" || firstPart == "articles") {
outputWikiPage(socket, pathParts);
} else {
outputHeader(socket, "404");
}
closeConnection(socket);
}
示例15: dataReceived
//recieves x,y,and paddle id from user
void Start::dataReceived()
{
QTcpSocket *sock = dynamic_cast<QTcpSocket*>(sender());
while (sock->canReadLine()) {
QString str = sock->readLine();
// qDebug() << str;
//World::getInstance()->updateUser(str); akjdhfa
//do something with the information that is coming in
// "3/Thomas/x/y/
// pos/username/x/y/
vector<QString>* info = World::getInstance()->split(str,'/');
int pos = info->at(0).toInt();
QString userName = info->at(1);
if (ok && clock < 50){
Player *inPlayer = World::getInstance()->getGamePlayer(pos);
inPlayer->setUsername(userName);
gameScreen->setUsernames();
if (clock > 50){
ok = false;
}
}
int x = info->at(2).toInt();
int y = info->at(3).toInt();
QPoint* mouseIn = new QPoint(x,y);
World::getInstance()->addMouse(mouseIn,pos);
World::getInstance()->setPlayerName(info->at(1), pos);
}
//}
//**********This is Schaub code that we can use as an example****************
/*QTcpSocket *sock = dynamic_cast<QTcpSocket*>(sender());
addToLog("Received data from socket ");
while (sock->canReadLine()) {
QString str = sock->readLine();
addToLog("-> " + str);
// send data to all connected clients
for (QObject *obj : server->children()) {
QTcpSocket *anotherSock = dynamic_cast<QTcpSocket*>(obj);
if (anotherSock != NULL)
anotherSock->write(str.toLocal8Bit());
}
}*/
}