QTCPSERVER:如何返回值



我正在qt上编写客户端/服务器通信系统。我正在使用qtcpserver和qtcpsocket。我正在从客户端发送一些信息,但是如何从服务器返回值?

客户端

QTcpSocket *socket = new QTcpSocket(this);
socket->connectToHost("MyHost", "MyPort");
socket->write("Hello from Client...");

服务器端

QtSimpleServer::QtSimpleServer(QObject *parent) : QTcpServer(parent)
{
    if (listen(QHostAddress::Any, "MyPort"))
    {
        qDebug() << "Listening...";
    }
    else
    {
        qDebug() << "Error while listening... " << errorString();
    }
}
void QtSimpleServer::incomingConnection(int handle)
{
    QTcpSocket *socket = new QTcpSocket();
    socket->setSocketDescriptor(handle);
    connect (socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
}
void QtSimpleServer::onReadyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    qDebug() << socket->readAll();
    socket->disconnectFromHost();
    socket->close();
    socket->deleteLater();
}

保存每个客户指针以进一步响应。

QVector<QTcpSocket*> clients;
void QtSimpleServer::incomingConnection(qintptr handle)
{
    QTcpSocket *socket = new QTcpSocket();
    socket->setSocketDescriptor(handle);
    connect (socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    clients << socket;
}
void QtSimpleServer::sendHelloToAllClient()
{
    foreach ( QTcpSocket * client, clients) {
        client->write(QString("Hello Client").toLatin1());
        client->flush();
    }
}

注意:

这只是一个简单的解决方案,可以显示保存范围内创建的对象的参考,稍后应引用。

如果您想练习更复杂的服务器/客户端应用程序,最好查看《螺纹》财富服务器示例和财富客户端示例

相关内容

  • 没有找到相关文章

最新更新