QTcpServer:如何返回值?

时间:2017-09-27 13:18:17

标签: qt qtcpsocket qtcpserver

我正在Qt上编写Client / Server通信系统。我正在使用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();
}

1 个答案:

答案 0 :(得分:2)

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

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

注意:

这只是一个简单的解决方案,可以显示为在作用域内创建的对象保存引用,并且应该在以后引用。

如果您想练习更复杂的服务器/客户端应用程序,最好查看Threaded Fortune Server ExampleFortune Client Example