1

I'm writing Client/Server communication system on Qt. I'm using QTcpServer and QtcpSocket. I'm sending some information from client side but how can I return value from server?

Client Side

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

Server Side

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();
}
Leri Gogsadze
  • 2,958
  • 2
  • 15
  • 24

1 Answers1

3

Save each client pointer for further respond.

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

Note:

This is only a simple solution to show save a reference for objects which is created inside a scope and should be referenced later.

if you want to practice more complex server/client application, It's better to have look on Threaded Fortune Server Example and Fortune Client Example

saeed
  • 2,477
  • 2
  • 23
  • 40