QT QTcpServer 未及时连接 [英] QT QTcpServer not connecting in time

查看:82
本文介绍了QT QTcpServer 未及时连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making a simple program that will 'connect' to itself and then send data. It starts a QTcpServer then waits for any incoming connections. I have a separate function that will in turn attempt to connect to this server at the localhost and port I decided on. This works when I open Telnet in the command prompt, but now in my actual program. Here is the code that I used (Some are snippets from other sources)

MainWindow.cpp:

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();
}

推荐答案

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

The source of your problem is, most likely, the pseudo-synchronous mess caused by waitFor methods. Get rid of them. Furthermore, you're not guaranteed anything about how many bytes you receive upon readyRead: it's perfectly normal to receive one byte at a time, in some circumstances, or really any number of bytes, including more bytes than you might expect. Your code must cope with that.

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

This is one example of such approach - it does what you want, asynchronously. That is another example that shows how to leverage state machines to write asynchronous communications code using an easy to read, declarative syntax.

这篇关于QT QTcpServer 未及时连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆