PDA

View Full Version : client sending data line by line to server in Qt



ajay
29th August 2012, 15:52
Hi,
I have a client as well as a server.I want to send .csv file to server line by line.I can do read the file line by line and write to the socket.But the problem is that server not receiving data line by line.it accept data after total reading of client's file.
I want client read a LINE and send it to server and server read that line.Again client read next line and send to server.
Any help???????
My client code like this....

client.h


class Client : public QObject
{
Q_OBJECT
public:
Client(QObject* parent = 0);
~Client();
void start(QString address, quint16 port);
// void Read(QString filename);

public slots:
void readData();
void sendData();
private:
QTcpSocket client;
QString line;
char *c_str2;

int LENGTH;
};


#endif // CLIENT_H


client.cpp


Client::Client(QObject* parent): QObject(parent)
{
connect(&client, SIGNAL(connected()),this, SLOT(readData()),Qt::DirectConnection);
connect(&client, SIGNAL(connected()),this, SLOT(sendData()),Qt::DirectConnection);
LENGTH =8;

}

Client::~Client()
{
client.close();
}

void Client::start(QString address, quint16 port)
{
QHostAddress addr(address);
client.connectToHost(addr, port);
}
void Client::readData()
{
QString mfilename ="/home/client2/Desktop/akde.csv";

//Read(mfilename);
// QByteArray ba = line.toLocal8Bit();
// c_str2 = ba.data();
// client.write(c_str2,5000);
QFile mfile(mfilename);

//if(!mfile.open(QFile::ReadOnly | QFile::Text))
if(mfile.open(QIODevice::ReadOnly | QIODevice::Text))
{
// qDebug() << "Could Not Open File For Reading!";
// return;
//}
QTextStream in(&mfile);

//QByteArray ba;
while (!in.atEnd()) {

line = in.readLine();
QByteArray ba = line.toLocal8Bit();
c_str2 = ba.data();
client.write(c_str2);
sleep(1);


qDebug() << line;

}

mfile.close();
}
}



main.cpp

#include <QtCore/QCoreApplication>
#include <client.h>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Client client;
client.start("112.165.1.2", 7350);

return a.exec();
}

ChrisW67
30th August 2012, 02:31
Qt networking is asynchronous: writing to a socket is non-blocking, and nothing is sent until your program reaches the Qt event loop. Your while() loop, with its misguided sleep() call, does not allow execution to reach the Qt event loop some time after the entire loop is completed. You need to design your program differently. There are plenty of examples in the docs and these forums.

ajay
30th August 2012, 11:18
Have your any suggestion regarding this???

ChrisW67
31st August 2012, 01:06
If by "suggestion" you mean "code I can copy and paste" then no. I have already suggested that you need to consult the docs/examples and rethink your design. I do not propose to do this for you. You will get help if you show how you are trying to rework it and ask specific questions.