ozzymado
ozzymado

Reputation: 998

Sending data from a server to a client

I have two projects, one for a server and one for a client. On the client, when I want to send data, I create a QTcpSocket member variable, and then send data using the write() method.

On the server, I receive the information, but I want to send information back to the client. Specifically I'm trying to validate a user, so I'm sending the user name and password that they log in with on the client to the server, and I want to check that data against the database saved on the server, and then send information back to the client to verify that the information was correct.

My problem is that I don't know how to send information from the server to the client. On the server, I have two member variables,QTcpServer server; and QTcpSocket* client;.

I've looked through documentation on QTcpServer and it has no equivalent to write() as far as I'm aware, and the QTcpSocket* is the client that's currently connected to the server.

I was thinking about creating a QTcpSocket variable on the server and sending information to the client the same way I send information to the sever, but that seems wrong because then the client would be behaving like a server, complete with a QTcpServer variable on the client.

How else would I go about doing this?

Upvotes: 3

Views: 4217

Answers (1)

Nejat
Nejat

Reputation: 32635

You should use QTcpServer to accept incoming TCP connections. First call listen() to wait for a connection :

QTcpServer* tcpServer = new QTcpServer();

connect(tcpServer, SIGNAL(newConnection()), this, SLOT(onNewConnection()));

if( !tcpServer->listen( QHostAddress::Any, port_no ) )
    qDebug() << "Couldn't listen to port";

This signal newConnection is emitted every time a new connection is available. So we connect the signal to a slot to get the server QTcpSocket object to communicate with the client :

void MyClass::onNewConnection()
{
    serverSocket = tcpServer->nextPendingConnection();

    connect(serverSocket, SIGNAL(readyRead()), this, SLOT(readSocket()));
}

You can now send data to the client socket, using the write method :

serverSocket->write("Hello!");

And read data when new data is arrived :

void MyClass::readSocket()
{
    QByteArray data = serverSocket->readAll();
    ...
}

Upvotes: 3

Related Questions