【问题标题】:QT QTcpServer not connecting in timeQT QTcpServer 没有及时连接
【发布时间】:2016-03-30 18:36:29
【问题描述】:

我正在制作一个简单的程序,它将“连接”到自身,然后发送数据。它启动一个 QTcpServer,然后等待任何传入的连接。我有一个单独的函数,它将依次尝试在我决定的本地主机和端口上连接到该服务器。这在我在命令提示符下打开 Telnet 时有效,但现在在我的实际程序中。这是我使用的代码(有些是来自其他来源的sn-ps)

MainWindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    server = new QTcpServer(this);
    //Initialize and start the server
    connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));
    if (!server->listen(QHostAddress::Any, 3665))
    {
        qDebug() << "Server failed to start!";
    }
    else
    {
        qDebug() << "Server started";
    }
    //Try to connect to the server
    connectToServer("127.0.0.1", qint16(3665));
}

MainWindow::~MainWindow()
{
    delete server;
    delete ui;
}

void MainWindow::connectToServer(QString host, qint16 port)
{
    qDebug() << "Connecting to " + host + " at port " + QString::number(port);
    QTcpSocket socket;
    socket.connectToHost(host, port);
    if (!socket.waitForConnected(5000))
    {
        qDebug() << socket.errorString();
    }
    while (socket.bytesAvailable() < (int)sizeof(quint16))
    {
        if (!socket.waitForReadyRead(5000))
        {
            qDebug() << socket.errorString();
        }
    }
    quint16 blockSize;
    QDataStream in(&socket);
    in.setVersion(QDataStream::Qt_5_5);
    in >> blockSize;
    while (socket.bytesAvailable() < blockSize)
    {
        if (!socket.waitForReadyRead(5000))
        {
            qDebug() << socket.errorString();
        }
    }
    QString fortune;
    in >> fortune;
    qDebug() << fortune;
}

void MainWindow::newConnection()
{
    qDebug() << "A connection has been found.";
    QTcpSocket *socket = server->nextPendingConnection();

    socket->write("hello client\r\n");
    socket->flush();
    socket->waitForBytesWritten(5000);
    socket->close();
}

【问题讨论】:

  • @KubaOber 好吧!我会努力的。当我在程序出错时添加 return(s) 时,我被难住了,并且在连接函数退出后,它仍然检测到有一个新连接。
  • 你需要使用事件而不是阻塞调用(waitFor...)。有关示例,请参见 ics.com/files/qtdocs/network-http.html
  • 确实信号就是我的意思:)

标签: c++ qt networking tcp


【解决方案1】:

问题的根源很可能是waitFor 方法引起的伪同步混乱。摆脱他们。此外,您无法保证在readyRead 上接收到多少字节:在某些情况下,一次接收一个字节或实际上是任意数量的字节是完全正常的,包括比您预期的更多的字节。您的代码必须应对这种情况。

This 是这种方法的一个例子 - 它可以异步执行您想要的操作。 That 是另一个示例,它展示了如何利用状态机使用易于阅读的声明性语法编写异步通信代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多