2

我创建了一个 hello-world 程序来帮助我理解 QTcpServer 和 QTcpSocket 是如何工作的。在其中,QTcpServer 接受新连接并将它们的readyRead()信号连接到MainWindow::onNewData()它们的新数据附加到纯文本控件的插槽。

问题是可以同时打开多个套接字。所以当我得到readyRead()信号并且我想用 读取数据时readAll(),我怎么知道是哪个套接字发出的呢?

这是代码的相关部分。我根本不在这里存储 QTcpSocket 指针,但即使我这样做了,我仍然不知道它们中的哪一个发出了信号。

    // constructor
    server = new QTcpServer(this);
    connect(server, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
    server->listen(QHostAddress::LocalHost, 3333);

void MainWindow::onNewConnection()
{
    QTcpSocket* socket = server->nextPendingConnection();
    connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
    connect(socket, SIGNAL(readyRead()), this, SLOT(onNewData()));
}

void MainWindow::onNewData()
{
    ui->plainTextEdit->appendPlainText(WHICH_SOCKET_EMITTED_IT()->readAll());
}
4

2 回答 2

3

最好的方法(在我看来)是实现你自己的Client类,它将封装QTcpSocket

class Client : public QObject
{
Q_OBJECT
public:
    Client(QTcpSocket *socket)
        : m_socket(socket)
{
    connect(socket, SIGNAL(readyRead()), this, SLOT(onNewData()));
}

private slots:
    void onNewData();

private:
    QTcpSocket *m_socket;
};

最简单的方法:QObject::sender()在槽函数中使用

于 2012-07-08T19:46:56.467 回答
1

Using a C++11 lambda functions in the connect statement, it's also possible to do this without the sender() function:

connect(socket, &QIODevice::readyRead,
        [this, socket()] { readData(socket) });

and a matching function (which does not need to be but can be a slot):

void foo::readData(QTcpSocket *socket)
{
    socket->whatever();
}
于 2018-09-05T08:18:04.567 回答