コード例 #1
0
ファイル: KCToolServer.cpp プロジェクト: ElliotZ/KanColleTool
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
0
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
0
ファイル: httpdaemon.cpp プロジェクト: sruthihsr/qwebsocket
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
0
ファイル: clientthread.cpp プロジェクト: sandsmark/impd
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
0
ファイル: Server.cpp プロジェクト: ocmwdt/usbwatcher
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
0
ファイル: client.cpp プロジェクト: w3sz/ghpsdr3-w3sz
void Client::readClient() {
    //qDebug()<<"Client::readClient";
    QTcpSocket* socket = (QTcpSocket*)sender();
    QByteArray buffer=socket->readLine();
    QString response=parseCommand(QString(buffer));
    socket->write(response.toLatin1());
}
コード例 #7
0
ファイル: Server.cpp プロジェクト: g0rny/MADN
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
0
ファイル: Serveur.cpp プロジェクト: CQuentin/QBomberMan
/**
 * 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
0
static QByteArray readLine(QTcpSocket &sock)
{
    while (!sock.canReadLine() && sock.waitForReadyRead());
    if (sock.state() != QAbstractSocket::ConnectedState)
        return QByteArray();
    return sock.readLine();
}
コード例 #10
0
ファイル: httpserver.cpp プロジェクト: MK-VTF/SoftWeb
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
0
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
0
ファイル: httpdaemon.cpp プロジェクト: NanoSim/Porto
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
0
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
0
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
0
void ctkSoapConnectionRunnable::readClient(QTcpSocket& socket)
{
  //qDebug() << socket->readAll();
  while (socket.canReadLine()) {
    QString line = socket.readLine();
    qDebug() << line;
    if (line.trimmed().isEmpty())
    {
      // Read the http body, which contains the soap message
      QByteArray body = socket.readAll();
      qDebug() << body;

      if (body.trimmed().isEmpty())
      {
        qDebug() << "Message body empty";
        return;
      }

      QtSoapMessage msg;
      if (!msg.setContent(body))
      {
        qDebug() << "QtSoap import failed:" << msg.errorString();
        return;
      }

      QtSoapMessage reply;
      emit incomingSoapMessage(msg, &reply);

      if (reply.isFault())
      {
        qDebug() << "QtSoap reply faulty";
        return;
      }

      qDebug() << "SOAP reply:";

      QString soapContent = reply.toXmlString();

      QByteArray block;
      block.append("HTTP/1.1 200 OK\n");
      block.append("Content-Type: text/xml;charset=utf-8\n");
      block.append("Content-Length: ").append(QString::number(soapContent.size())).append("\n");
      block.append("\n");

      block.append(soapContent);

      qDebug() << block;

      socket.write(block);

    }
  }
}
コード例 #16
0
ファイル: imap.cpp プロジェクト: vohulg/newimapgui
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
}
コード例 #17
0
void LCDServer::readSocket()
{
    QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
    m_lastSocket = socket;

    while(socket->canReadLine())
    {
        QString incoming_data = socket->readLine();
        incoming_data = incoming_data.replace( QRegExp("\n"), "" );
        incoming_data = incoming_data.replace( QRegExp("\r"), "" );
        incoming_data.simplified();
        QStringList tokens = parseCommand(incoming_data);
        parseTokens(tokens, socket);
    }
}
コード例 #18
0
void TestHTTPServer::readyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (!socket || socket->state() == QTcpSocket::ClosingState)
        return;

    if (!m_directories.isEmpty()) {
        serveGET(socket, socket->readAll());
        return;
    }

    if (m_state == Failed || (m_waitData.body.isEmpty() && m_waitData.headers.count() == 0)) {
        qWarning() << "TestHTTPServer: Unexpected data" << socket->readAll();
        return;
    }

    if (m_state == AwaitingHeader) {
        QByteArray line;
        while (!(line = socket->readLine()).isEmpty()) {
            line.replace('\r', "");
            if (line.at(0) == '\n') {
                m_state = AwaitingData;
                m_data += socket->readAll();
                break;
            } else {
                if (!m_waitData.headers.contains(line)) {
                    qWarning() << "TestHTTPServer: Unexpected header:" << line
                               << "\nExpected headers: " << m_waitData.headers;
                    m_state = Failed;
                    socket->disconnectFromHost();
                    return;
                }
            }
        }
    }  else {
        m_data += socket->readAll();
    }

    if (!m_data.isEmpty() || m_waitData.body.isEmpty()) {
        if (m_waitData.body != m_data) {
            qWarning() << "TestHTTPServer: Unexpected data" << m_data << "\nExpected: " << m_waitData.body;
            m_state = Failed;
        } else {
            socket->write(m_replyData);
        }
        socket->disconnectFromHost();
    }
}
コード例 #19
0
ファイル: httpdaemon.cpp プロジェクト: mzanetti/guh
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";
            }
        }
    }
}
コード例 #20
0
//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();
}
コード例 #21
0
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);
}
コード例 #22
0
ファイル: start.cpp プロジェクト: jposchel/all-4-pong
//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());
        }

    }*/
}
コード例 #23
0
ファイル: tst_qiodevice.cpp プロジェクト: KDE/android-qt
//----------------------------------------------------------------------------------
void tst_QIODevice::constructing_QTcpSocket()
{
#if defined(Q_OS_WINCE) && defined(WINCE_EMULATOR_TEST)
    QSKIP("Networking tests in a WinCE emulator are unstable", SkipAll);
#endif
    QTcpSocket socket;
    QIODevice *device = &socket;

    QVERIFY(!device->isOpen());

    socket.connectToHost(QtNetworkSettings::serverName(), 143);
    QVERIFY(socket.waitForConnected(5000));
    QVERIFY(device->isOpen());

    while (!device->canReadLine())
        QVERIFY(device->waitForReadyRead(5000));

    char buf[1024];
    memset(buf, 0, sizeof(buf));
    qlonglong lineLength = device->readLine(buf, sizeof(buf));
    QVERIFY(lineLength > 0);
    QCOMPARE(socket.pos(), qlonglong(0));

    socket.close();
    socket.connectToHost(QtNetworkSettings::serverName(), 143);
    QVERIFY(socket.waitForConnected(5000));
    QVERIFY(device->isOpen());

    while (!device->canReadLine())
        QVERIFY(device->waitForReadyRead(5000));

    char buf2[1024];
    memset(buf2, 0, sizeof(buf2));
    QCOMPARE(socket.readLine(buf2, sizeof(buf2)), lineLength);

    char *c1 = buf;
    char *c2 = buf2;
    while (*c1 && *c2) {
        QCOMPARE(*c1, *c2);
        ++c1;
        ++c2;
    }
    QCOMPARE(*c1, *c2);
}
コード例 #24
0
ファイル: httprequest.cpp プロジェクト: UIKit0/mscoreserver
void HttpRequest::readRequest(QTcpSocket& socket)
      {
      int toRead = maxSize - currentSize + 1; // allow one byte more to be able to detect overflow
      QByteArray newData = socket.readLine(toRead).trimmed();
      currentSize += newData.size();
      if (!newData.isEmpty()) {
            QList<QByteArray> list = newData.split(' ');
            if (list.count() != 3 || !list.at(2).contains("HTTP")) {
                  qWarning("HttpRequest: received broken HTTP request, invalid first line");
                  status = abort;
                  }
            else {
                  method = list.at(0);
                  path = list.at(1);
                  version = list.at(2);
                  status = waitForHeader;
                  }
            }
      }
コード例 #25
0
void HttpServer::readClient()
{
    QTcpSocket * socket = (QTcpSocket*)sender();
    if (socket->canReadLine())
    {
        QTextStream os(socket);
        os.setAutoDetectUnicode(true);

        QStringList tokens = QString(socket->readLine()).split(QRegExp("[ \r\n][ \r\n]*"));
        if (tokens[0] == "GET")
        {
            QStringList resources = tokens[1].split(QRegExp("\\?"));
            if (resources.count() == 2)
            {
                if (resources[0] == "/canvas.html")
                {
                    QStringList args = resources[1].split(QRegExp("&(amp){0}"));
                    foreach (QString arg, args)
                    {
                        QStringList kv = arg.split("=");
                        if (kv.count() == 2 && kv[0] == "app")
                        {
                            if (ACLProvider::instance()->isAccepted(kv[1]))
                            {
                                qDebug() << "Sending canvas.html page";
                                this->sendCanvas(os, kv[1]);
                                goto close_socket;
                            }
                            else
                            {
                                this->sendRejection(os, kv[1]);
                                goto close_socket;
                            }
                        }
                    }
                    qDebug() << "Cannot find application name";
                    this->sendStatus(os, 400);
                    goto close_socket;
                }
コード例 #26
0
ファイル: ChatBoxServer.cpp プロジェクト: nitul1991/ChatBox
void ChatBoxServer::readyRead()
{
    // Used to retrieve a pointer to the client
    QTcpSocket *client = (QTcpSocket*)sender();
    
    while(client->canReadLine())
    {
        QString line = QString::fromUtf8(client->readLine()).trimmed();
        qDebug() << "Read line:" << line;

        QRegExp meRegex("^/me:(.*)$");

        if(meRegex.indexIn(line) != -1)
        {
            QString user = meRegex.cap(1);
            // Insert username into QMap
            users[client] = user;
            
            foreach(QTcpSocket *client, clients)
                client->write(QString("Server:" + user + " has joined.\n").toUtf8());
            sendUserList();
        }
        else if(users.contains(client))
        {
            QString message = line;
            QString user = users[client];
            qDebug() << "User:"******"Message:" << message;

            foreach(QTcpSocket *otherClient, clients)
                otherClient->write(QString(user + ":" + message + "\n").toUtf8());
        }
        else
        {
            qWarning() << "Got bad message from client:" << client->peerAddress().toString() << line;
        }
    }
}
コード例 #27
0
void ServerPanelRpcServer::ReadClient() {
    // Check to see if the server is paused
    if (this->bDisabled) {
        // We're done
        return;
    }
    // Open the socket
    QTcpSocket* cSocket = (QTcpSocket*) sender();
    // Can we read the socket
    if (cSocket->canReadLine()) {
        // Grab the headers
        QStringList qslTokens = QString(cSocket->readLine().split(QRegExp("[ \r\n][ \r\n]*")));
        // What reqeust was sent
        if (qslTokens[0] == "GET") {         // GET
            // Create a new text stream for the socket
            QTextStream cSocketStream(cSocket);
            // Automagically detect the use of unicode
            cSocketStream.setAutoDetectUnicode(true);
            // Send a response
            cSocketStream << "HTTP/1.0 200 Ok\r\n";
            cSocketStream << "Content-Type: application/json; charset=\"utf-8\"\r\n";
            cSocketStream << "\r\n";
            cSocketStream << "{\"sServerResponse\":\"Good!\", \"sServerTime\":\"";
            cSocketStream << QDateTime::currentDateTime().toString() << "\"}\n";
        } else if (qslTokens[0] == "POST") { // POST

        } else {                             // Unknown/Unsupported

        }
    }
    // Close the socket
    cSocket->close();
    // Check the state of the socket
    if (cSocket->state() == QTcpSocket::UnconnectedState) {
        // Remove the socket
        delete cSocket;
    }
}
コード例 #28
0
ファイル: clcserver.cpp プロジェクト: hl037/CLCBrowser
void CLCServer::readConnection()
{
   QTcpSocket * sock = nextPendingConnection();
   sock->waitForReadyRead();
   QByteArray b = sock->readLine();
   if(b.isEmpty()) return;

   const char * cmd = b.data();

   Arguments * a = parse_commandline(cmd);

   QStringList l;
   l << "CLCBrowser";

   for(int i=1 ; i<a->argc ; ++i)
   {
      l << a->argv[i];
   }
   Arguments_destroy(a);

   parseArgs(l, sock);
   sock->close();
}
コード例 #29
0
ファイル: servernet.cpp プロジェクト: klimoqu/Arawn
void Servernet::readyRead()
{
	QTcpSocket *client =(QTcpSocket*)sender();
	while(client->canReadLine())
	{
		QString line = QString::fromUtf8(client->readLine()).trimmed();
		QRegExp meRegex("^/me:(.*)$");
		QRegExp commandRegex("^/command:(.*)$");
		if(meRegex.indexIn(line) != -1 && players.size()<=this->playernumber)		///az auth rész
		{
			QString user = meRegex.cap(1);
			players.insert(client,user);
			Command c((uchar)clients.size(),(uchar)255,(int)survive?0:1);
			client->write(c.ToString().toUtf8());
			client->flush();
			emit NewPlayerConnected();
			sendusernames();
			if(players.size()==this->playernumber)emit AllPlayersConnected();
		}
		else if(commandRegex.indexIn(line) != -1)									///command jön a klienstől
		{
			uchar id,type;
			int msg;
			QStringList command = commandRegex.cap(1).split(' ');
			id=(uchar)command.at(0).toInt();
			type=(uchar)command.at(1).toInt();
			msg=command.at(2).toInt();
			emit CommandReceivedFromClients(Command(id,type,msg));
		}
		else																		///egyéb hülyeség jön a klienstől
		{
			qDebug() << "hülyeség jött";
		}
	}

}
コード例 #30
0
ファイル: httpServer.cpp プロジェクト: Darknautilus/tp-vod
void httpServer::getClientRequest()
{
	QTcpSocket *client = qobject_cast<QTcpSocket *>(sender());	
	if(client->canReadLine())
	{
		QStringList lines = QString(client->readLine()).split(QRegExp("[ \r\n][ \r\n]*"));
		if(lines[0] == "GET")
		{
			viewMessage(QString::fromUtf8("Envoi du catalogue à ")+client->peerAddress().toString()+":"+QString::number(client->peerPort()));
			QFile catalogue(QCoreApplication::applicationDirPath()+"/catalog.tmp");
			catalogue.open(QIODevice::ReadOnly | QIODevice::Text);
			QTextStream os(client);
			QTextStream is(&catalogue);
			os << "HTTP/1.1 200 OK\r\nServer: TP_Serveur_3208\r\nConnection: Keep-Alive\r\nContent-Type: text/txt\r\nContent-Length: " << catalogue.size() << "\r\n\r\n";
			QString line = is.readLine();
			while(!line.isNull())
			{
				os << line.toLocal8Bit().constData() << "\r\n";
				line = is.readLine();
			}
			catalogue.close();
		}
	}	
}