2014-09-28 2 views
0

Pi를 계산하는 프로그램을 작성했습니다. 3.14 이후의 자릿수를 근사합니다 ...Qt : 서버가 변경 값을 브로드 캐스팅해야하고 클라이언트가 청취해야합니다.

이제 내 프로그램에서 어떤 위치가 계산되는지 알고 싶습니다. 그러나 나는 컴퓨터 앞에서 기다리고 싶지 않다. 따라서 QTcpServer와 클라이언트로 서버에 액세스 할 수있는 가능성을 구현합니다. 연결이 정상적으로 작동합니다. 다음 단계에서는 Pi의 현재 값과 숫자를 서버를 통해 브로드 캐스트로 보내고 싶습니다. 클라이언트가 서버에 연결할 때마다 클라이언트는이 정보를 읽어야합니다. 정보는 지속적으로 업데이트되며 클라이언트는 정보가 연결되어있는 한이 정보를 받아야합니다. 클라이언트의 수신 정보를 업데이트하려면 알림 또는 폴링 기능이 필요합니다. 정보 (서버) 및 업데이트 알림 (클라이언트)의 브로드 캐스트를 어떻게 실현할 수 있습니까?

헤더

#include <QObject> 
#include <QDebug> 
#include <QTcpServer> 
#include <QTcpSocket> 

class HTTPServer : public QObject 
{ 
    Q_OBJECT 
public: 
    explicit HTTPServer(QObject *parent = 0); 

    int value; 

signals: 

public slots: 
    void newConnection(); 
    void readClient(); 

private: 
    QTcpServer *server; 
    QTcpSocket *socket; 

}; 

CPP

#include "httpserver.h" 

    HTTPServer::HTTPServer(QObject *parent) : 
     QObject(parent) 
    { 
     server = new QTcpServer(this); 

     connect(server, SIGNAL(newConnection()), this, SLOT(newConnection())); 

     if(!server->listen(QHostAddress::Any, 9999)) 
      qDebug() << "Server could not started!"; 
     else 
      qDebug() << "Server started and listening ..."; 
    } 

    void HTTPServer::calculate() 
    { 
     for(int i = 0; i < 100000000; i++) 
      value = i; 
    } 

    void HTTPServer::newConnection() 
    { 
     socket = server->nextPendingConnection(); 

     socket->write("client connected\r\n"); 
     socket->flush(); 
     socket->waitForBytesWritten(3000); 

     this->calculate(); 

     char buffer [50]; 
     sprintf(buffer, "%d\r\n", value); 
     socket->write(buffer); 
     socket->flush(); 
     socket->waitForBytesWritten(3000); 

     connect(socket, SIGNAL(readyRead()), this, SLOT(readClient()), Qt::DirectConnection); 
    } 

    void HTTPServer::readClient() 
    { 
     QByteArray Data = socket->readAll(); 

     qDebug() << "Data in: " << Data; 

     socket->write(Data); 

     //if ((std::string stdString(Data.constData(), Data.length())) == "quitServer") 
     // server->close(); 
    } 

int value는 파이 값을 시뮬레이션한다.

답변

0

[업데이트되었습니다] QUdpSocket으로 방송을 할 수 있습니다. Qt SDK에는 broadcasting implementation (브로드 캐스트 receiversender 예제)의 훌륭한 예가 있습니다.

또한 방송용으로 TCP 프로토콜을 사용할 수 없습니다.

+0

안녕하세요, 지금 당장하고있는 내용입니다. 하지만 클라이언트가 서버에 연결하면됩니다. 내가 찾고있는 것은 업데이트 기능입니다. 변경된 각 값에 대해 정보는 서버에 의해 브로드 캐스팅되어 클라이언트에 의해 수신되어야합니다. – 3ef9g

+0

안녕하세요, 제 답변을 업데이트했습니다. –

+0

감사합니다. 이것이 도움이 될 것이라고 생각합니다. QTcpSocket을 통해 정보를 보낼 수없는 이유는 무엇입니까? 그것은 이미 쓰고 플러시로 작동합니다 ... socket-> write ("client connected \ r \ n"); – 3ef9g