abdallah allam
abdallah allam

Reputation: 73

QTcpSocket unknown error

I want to send data from client to server, when i try to connect to serevr, client show unkown error, and no data sent

its show only empty string "",

any help will be appreciated.

here is the code:

//client

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    tcpSocket = new QTcpSocket(this);

    connect(tcpSocket, SIGNAL(connected()), this, SLOT(connected()));

    QHostAddress ha;
    ha.setAddress("myIP");

    tcpSocket->connectToHost(ha, 6401);

    if(!tcpSocket->waitForConnected(3000)) {
        ui->lineEdit->setText(tcpSocket->errorString());
    }
    else
        ui->lineEdit->setText("connected");
}

void Widget::connected()
{
   tcpSocket->write("hello this is client\r\n");
   tcpSocket->flush();
   tcpSocket->waitForBytesWritten(3000);

    tcpSocket->close();
}

//server

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    tcpServer = new QTcpServer(this);

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

    if(!tcpServer->listen(QHostAddress::Any, 6401)) {
           ui->lineEdit->setText("server not started");
       }
       else
           ui->lineEdit->setText("server started");
}

void Widget::newConnection()
{
    QTcpSocket *tcpSocket= tcpServer->nextPendingConnection();

    qDebug() << tcpSocket->readAll();
    tcpSocket->waitForReadyRead(3000);

    tcpSocket->close();
}

Upvotes: 1

Views: 1069

Answers (1)

abdallah allam
abdallah allam

Reputation: 73

here is the problem:

//wrong order

qDebug() << tcpSocket->readAll();
tcpSocket->waitForReadyRead(3000);

//correct order:

tcpSocket->waitForReadyRead(3000);
qDebug() << tcpSocket->readAll();

Upvotes: 1

Related Questions