首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QTcpServer:如何返回值?

QTcpServer:如何返回值?
EN

Stack Overflow用户
提问于 2017-09-27 13:18:17
回答 1查看 386关注 0票数 1

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

客户端

代码语言:javascript
复制
QTcpSocket *socket = new QTcpSocket(this);
socket->connectToHost("MyHost", "MyPort");
socket->write("Hello from Client...");

服务器端

代码语言:javascript
复制
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();
}
EN

回答 1

Stack Overflow用户

发布于 2017-09-27 13:43:50

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

代码语言:javascript
复制
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();
    }
}

注:

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

如果您想实践更复杂的服务器/客户端应用程序,最好先看看线程“财富”服务器示例财富客户端示例

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46448936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档