QTcpSocket state always connected, even unplugging ethernet wire

前端 未结 4 1474
-上瘾入骨i
-上瘾入骨i 2020-12-08 01:11

I have a QTcpSocket and I am reading into a loop. Each time a full packet has been read, or there has been an error, I manually check the status of the socket inside the loo

4条回答
  •  星月不相逢
    2020-12-08 01:23

    try my template of client in Qt:

    class Client: public QTcpSocket {
       Q_OBJECT
    public:
        Client(const QHostAddress&, int port, QObject* parent= 0);
        ~Client();
        void Client::sendMessage(const QString& );
    private slots:
        void readyRead();
        void connected();
    public slots:
        void doConnect();
    };
    

    on cpp:

    void Client::readyRead() {
    
        // if you need to read the answer of server..
        while (this->canReadLine()) {
        }
    }
    
    void Client::doConnect() {
        this->connectToHost(ip_, port_);
        qDebug() << " INFO : " << QDateTime::currentDateTime()
                << " : CONNESSIONE...";
    }
    
    void Client::connected() {
        qDebug() << " INFO : " << QDateTime::currentDateTime() << " : CONNESSO a "
                << ip_ << " e PORTA " << port_;
        //do stuff if you need
    }
    
    
    void Client::sendMessage(const QString& message) {
        this->write(message.toUtf8());
        this->write("\n"); //every message ends with a new line
    }
    

    i omitted some code as constructor and slots connections.. try with this and if it doesn t work maybe there is something wrong on server side..

提交回复
热议问题