【问题标题】:QTcpServer: how to return value?QTcpServer:如何返回值?
【发布时间】:2018-03-09 00:06:21
【问题描述】:

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

【问题讨论】:

  • 您可以使用socket-&gt;write 方法。顺便说一句,您应该注意,该数据包可能是碎片化的,并且不能保证您将使用 readAll() 中的一个来接收所有数据。
  • 如何从服务器返回值?什么价值?您可能需要保存客户端指针以供进一步使用
  • @saeed 例如:我想向客户端发送“来自服务器的你好”。我该怎么做?
  • @J.Doe 如果您认为我的帖子是正确的,您可以接受。
  • @saeed 我没有检查,因为我找到了另一种方法,但无论如何 +1..

标签: qt qtcpsocket qtcpserver


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 2012-07-24
    相关资源
    最近更新 更多