首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QTcpSocket未知误差

QTcpSocket未知误差
EN

Stack Overflow用户
提问于 2016-11-03 09:47:53
回答 1查看 922关注 0票数 1

我想从客户端发送数据到服务器,当我试图连接到serevr时,客户端显示未知错误,而没有发送数据。

它只显示空字符串"",

任何帮助都将不胜感激。

以下是代码:

//客户

代码语言:javascript
复制
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();
}

//服务器

代码语言:javascript
复制
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();
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-03 10:26:34

以下是问题所在:

//错误的顺序

代码语言:javascript
复制
qDebug() << tcpSocket->readAll();
tcpSocket->waitForReadyRead(3000);

//正确顺序:

代码语言:javascript
复制
tcpSocket->waitForReadyRead(3000);
qDebug() << tcpSocket->readAll();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40398315

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档