Results 1 to 8 of 8

Thread: Don't receive data on a TCP-IP server client connection

  1. #1
    Join Date
    May 2015
    Posts
    4
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Don't receive data on a TCP-IP server client connection

    Hi,

    I am quite new using QT and I am trying to implement a TPC-IP server- client. The server has to read every 0.1sec a line of a file with latitude and longitude and send it to the client. But right now I can connect server and client but the client receive nothing. Could someone help me?? Thanks in advance.

    SERVER
    main.cpp
    Qt Code:
    1. #include <iostream>
    2. #include <QCoreApplication>
    3. #include "server.h"
    4.  
    5. int main(int argc, char *argv[]){
    6. QCoreApplication app(argc, argv);
    7. QString ipaddress = QString(argv[1]);
    8. int port = atoi(argv[2]);
    9. Server* server = new Server("127.0.0.1", 1234);
    10. int retVal = app.exec();
    11. return retVal;
    12. }
    To copy to clipboard, switch view to plain text mode 

    server.cpp

    Qt Code:
    1. include "server.h"
    2. #include <iostream>
    3. #include <QTcpServer>
    4. #include <QTcpSocket>
    5. #include <QTimer>
    6. #include <QDateTime>
    7. #include <QSettings>
    8. #include "readdata.h"
    9.  
    10. Server::Server(QString ipAddress, int port, QObject *parent) :
    11. QObject(parent), mTcpServer(0), mTcpSocket(0)
    12. {
    13. mTcpServer = new QTcpServer(this);
    14. connect(mTcpServer, SIGNAL(newConnection()), this, SLOT(newConnectionSlot()));
    15. if (!mTcpServer->listen(QHostAddress(ipAddress), port)) {
    16. std::cout << "Unable to start the server: " << mTcpServer->errorString().toStdString() << std::endl;
    17. return;
    18. }
    19.  
    20. std::cout << "The server is running on\n\nIP: "<< ipAddress.toStdString()
    21. << "\nport: " << mTcpServer->serverPort() << "\n\nRun the Client now.\n" << std::endl;
    22. }
    23.  
    24. void Server::newConnectionSlot()
    25. {
    26. mTcpSocket = mTcpServer->nextPendingConnection();
    27. connect(mTcpSocket, SIGNAL(disconnected()),
    28. mTcpSocket, SLOT(deleteLater()));
    29.  
    30. // setup timer to send data at a given interval
    31. mSendTimer = new QTimer(this);
    32. connect(mSendTimer, SIGNAL(timeout()),
    33. this, SLOT(sendSlot()));
    34. mSendTimer->start(40);
    35. }
    36.  
    37. void Server::sendSlot()
    38. {
    39. if(!mTcpSocket)
    40. return;
    41.  
    42. readPathData("/home/jorge/Desktop/INStest.kml", &latitude, &longitude);
    43.  
    44. QByteArray block;
    45. QDataStream out(&block, QIODevice::WriteOnly);
    46. out.setVersion(QDataStream::Qt_4_0);
    47. out << (quint16)0;
    48.  
    49. for(int i=0; i < latitude.size(); i++){
    50. positionTest.append(QString::number(latitude[i]) + " " + QString::number(longitude[i]) + /*" " + QString::number(height[i])+*/ "\n");
    51. data << positionTest[i];
    52. out << data.at(qrand() % data.size());
    53. out.device()->seek(0);
    54. out << (quint16)(block.size() - sizeof(quint16));
    55. qint64 written_lat = mTcpSocket->write(block, block.size());
    56. }
    57. }
    To copy to clipboard, switch view to plain text mode 

    server.h
    Qt Code:
    1. #ifndef SERVER_H_
    2. #define SERVER_H_
    3.  
    4. #include <QObject>
    5. #include <QVector>
    6. #include <QStringList>
    7.  
    8. QT_BEGIN_NAMESPACE
    9. class QTcpServer;
    10. class QNetworkSession;
    11. class QTcpSocket;
    12. class QTimer;
    13. QT_END_NAMESPACE
    14.  
    15. class Server : public QObject
    16. {
    17. Q_OBJECT
    18.  
    19. public:
    20. Server(QString ipAddress, int port, QObject *parent = 0);
    21.  
    22. private slots:
    23. void newConnectionSlot();
    24. void sendSlot();
    25.  
    26. private:
    27. QTcpServer *mTcpServer;
    28. QTcpSocket *mTcpSocket;
    29. QTimer *mSendTimer;
    30.  
    31.  
    32. QVector<double> latitude;
    33. QVector<double> longitude;
    34. QVector<double> height;
    35. QString latitudeTest;
    36. QString longitudeTest;
    37. QString heightTest;
    38. QVector<QString> positionTest;
    39.  
    40. };
    41.  
    42. #endif /* SERVER_H_ */
    To copy to clipboard, switch view to plain text mode 

    readData.cpp
    Qt Code:
    1. #include <QFile>
    2. #include <QTextStream>
    3. #include "readdata.h"
    4. #include "QPoint"
    5.  
    6. void readPathData(QString filename, QVector<double>* latitude, QVector<double>* longitude)
    7. {
    8. QFile file;
    9. file.setFileName(filename);
    10. file.open(QIODevice::ReadOnly);
    11. QByteArray line = file.readLine(); //Read two first lines of the .kml file
    12. line = file.readLine();
    13.  
    14. while (!file.atEnd()) {
    15. QByteArray line = file.readLine();
    16. if(line[0] != '<')
    17. {
    18. double lon;
    19. double lat;
    20. double hei;
    21.  
    22. QList<QByteArray> values = line.split(',');
    23.  
    24. hei = atof(values.at(2).constData());
    25. lat = atof(values.at(1).constData());
    26. lon = atof(values.at(0).constData());
    27.  
    28. if (latitude)
    29. latitude->append(lat);
    30.  
    31.  
    32. if (longitude)
    33. longitude->append(lon);
    34. }
    35. }
    36. file.close();
    37. }
    To copy to clipboard, switch view to plain text mode 

    readData.h
    Qt Code:
    1. #include <QString>
    2. #include <QVector>
    3.  
    4. #ifndef READDATA
    5. #define READDATA
    6.  
    7. void readPathData(QString filename, QVector<double>* latitude, QVector<double>* longitude/*, QVector<double>* height*/);
    8.  
    9. #endif // READDATA
    To copy to clipboard, switch view to plain text mode 

    CLIENT
    main.cpp
    Qt Code:
    1. #include <iostream>
    2. #include <QCoreApplication>
    3.  
    4. #include "client.h"
    5.  
    6. int main(int argc, char *argv[]){
    7. QCoreApplication app(argc, argv);
    8. QString ipaddress = QString(argv[1]);
    9. int port = atoi(argv[2]);
    10. Client* client = new Client("127.0.0.1", 1234);
    11. int retVal = app.exec();
    12. }
    To copy to clipboard, switch view to plain text mode 

    client.cpp
    Qt Code:
    1. #include "client.h"
    2. #include <iostream>
    3. #include <QTcpSocket>
    4. #include <QSettings>
    5. #include <QDateTime>
    6.  
    7. Client::Client(QString ipAddress, int port, QObject *parent):
    8. QObject(parent), mTcpSocket(0), mIpAddress(ipAddress), mPort(port)
    9. {
    10. mTcpSocket = new QTcpSocket(this);
    11. connect(mTcpSocket, SIGNAL(readyRead()),
    12. this, SLOT(readSlot()));
    13. connect(mTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
    14. this, SLOT(displayErrorSlot(QAbstractSocket::SocketError)));
    15.  
    16. std::cout << "Connecting to ip: " << mIpAddress.toStdString() << " port: " << mPort << std::endl;
    17. mTcpSocket->connectToHost(mIpAddress, mPort);
    18. }
    19.  
    20. void Client::readSlot()
    21. {
    22. static qint64 starttime = QDateTime::currentMSecsSinceEpoch();
    23. static int frames = 0;
    24.  
    25. qint64 blockSize = 1440000; //in bytes
    26.  
    27. QDataStream in(mTcpSocket);
    28.  
    29. if (blockSize == 0) {
    30. if (mTcpSocket->bytesAvailable() < (int)sizeof(quint32))
    31. return;
    32. in >> blockSize;
    33. }
    34.  
    35. if (mTcpSocket->bytesAvailable() < 38)
    36. return;
    37.  
    38. QString nextPos;
    39. in >> nextPos;
    40. currentPos = nextPos;
    41.  
    42. char* data = (char*) malloc(blockSize);
    43. qint64 bytesRead = mTcpSocket->read(data, blockSize);
    44. free(data);
    45. qDebug() << "Data" << data;
    46. qDebug() << "Position" << currentPos;
    47.  
    48. }
    49.  
    50. void Client::displayErrorSlot(QAbstractSocket::SocketError socketError)
    51. {
    52. switch (socketError) {
    53. case QAbstractSocket::RemoteHostClosedError:
    54. break;
    55. case QAbstractSocket::HostNotFoundError:
    56. std::cout << "The host was not found. Please check the "
    57. "host name and port settings."<< std::endl;
    58. break;
    59. case QAbstractSocket::ConnectionRefusedError:
    60. std::cout << "The connection was refused by the peer. "
    61. "Make sure the fortune server is running, "
    62. "and check that the host name and port "
    63. "settings are correct."<< std::endl;
    64. break;
    65. default:
    66. std::cout << "The following error occurred: " << mTcpSocket->errorString().toStdString() << std::endl;
    67. break;
    68. }
    69. }
    To copy to clipboard, switch view to plain text mode 

    client.h
    Qt Code:
    1. #ifndef CLIENT_H_
    2. #define CLIENT_H_
    3.  
    4. #include <QObject>
    5. #include <QAbstractSocket>
    6.  
    7. QT_BEGIN_NAMESPACE
    8. class QTcpSocket;
    9. QT_END_NAMESPACE
    10.  
    11. class Client : public QObject
    12. {
    13. Q_OBJECT
    14. public:
    15. Client(QString ipAddress, int port, QObject *parent=0);
    16.  
    17. private slots:
    18. void readSlot();
    19. void displayErrorSlot(QAbstractSocket::SocketError);
    20.  
    21. private:
    22. QTcpSocket *mTcpSocket;
    23. QString mIpAddress;
    24. int mPort;
    25. QString currentPos;
    26. };
    27.  
    28. #endif /* CLIENT_H_ */
    To copy to clipboard, switch view to plain text mode 

  2. #2
    Join Date
    Oct 2009
    Posts
    483
    Thanked 97 Times in 94 Posts
    Qt products
    Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: Don't receive data on a TCP-IP server client connection

    Your code is so broken I wonder where to begin. Here are some of the things I observed:

    Server:
    main() leaks the Server object (which is bad practice, but may not be noticeable).
    The server only sends data to the latest connected client, and does so at a rate growing with the number N of clients that have connected to the server since it started.
    The server leaks memory like there is no tomorrow. Every 40/N ms on average, it completely parses the file, appends a new copy of the parsed data to latitude, longitude, positionTest, and data, and then proceeds to send tons of blocks of data to the latest connected client.
    I wonder how long the server runs before it runs out of memory.

    Client:
    main() leaks the Client object (which is bad practice, but may not be noticeable).
    readSlot() parses some data it receives according to a different protocol than the one used by the server. It tests whether 1440000 == 0 (I have no idea why). It tricks qDebug() into reading from deallocated memory.

    I will stop here because I believe you need to start over. First try to build a very small example with a server that sends one byte to a client.

  3. #3
    Join Date
    May 2015
    Posts
    4
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Re: Don't receive data on a TCP-IP server client connection

    Okay, thanks for the answer. I will try to start with something easier. Do you know where can I find an example for that?
    Last edited by JorgeQT; 19th May 2015 at 16:19.

  4. #4
    Join Date
    Oct 2009
    Posts
    483
    Thanked 97 Times in 94 Posts
    Qt products
    Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: Don't receive data on a TCP-IP server client connection

    Sure, Qt's networking examples are a good place to start. I suggest you focus on one aspect of the problem at a time.

    In particular, have a look at the Fortune Server and Client. These examples are very simple because the connections do not persist: the server accepts a connection, immediately writes some data, closes the socket, and forgets about it. Still, they show how to serialize and deserialize a QString.

    Then, maybe, improve on this example by having persistent connections, e.g. by having the server send a simple message whenever a timer ticks. This will teach you how to manage several concurrent client connections in the server (maybe each with its own timer). Or you could set up the QTcpServer so that it never accepts more than one client connection at a time, if this is acceptable to you; that would allow a much simpler design.

    After you have done all that, you could focus on the issue of transmitting data gradually read from a file.

  5. #5
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    33,359
    Thanks
    3
    Thanked 5,015 Times in 4,792 Posts
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows Android Maemo/MeeGo
    Wiki edits
    10

    Default Re: Don't receive data on a TCP-IP server client connection

    Quote Originally Posted by yeye_olive View Post
    I will stop here because I believe you need to start over. First try to build a very small example with a server that sends one byte to a client.
    I will also add that the client repeats a totally broken read pattern where it reads 4 bytes and then forgets them if more data is not available completely desyncing the connection.

    Remember that the fortune server and fortune client examples are just examples, do not follow their architecture for any real-world applications, those examples are totally broken when it comes to security and robustness!
    Your biological and technological distinctiveness will be added to our own. Resistance is futile.

    Please ask Qt related questions on the forum and not using private messages or visitor messages.


  6. #6
    Join Date
    May 2015
    Posts
    4
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Re: Don't receive data on a TCP-IP server client connection

    Hi,

    Right now I am able to send bytes from the server to the client, but I don't know how I can keep alive the connection. Any suggestions?

  7. #7
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    33,359
    Thanks
    3
    Thanked 5,015 Times in 4,792 Posts
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows Android Maemo/MeeGo
    Wiki edits
    10

    Default Re: Don't receive data on a TCP-IP server client connection

    If you want keep-alive for less than the system socket timeout setting (usually at least 10 minutes or so), you don't have to do anything. If you want to support silence for longer periods of times, you will need to set the keep-alive flag on the socket with setSocketOption().
    Your biological and technological distinctiveness will be added to our own. Resistance is futile.

    Please ask Qt related questions on the forum and not using private messages or visitor messages.


  8. #8
    Join Date
    May 2015
    Posts
    4
    Qt products
    Qt5
    Platforms
    Unix/X11

    Default Re: Don't receive data on a TCP-IP server client connection

    Thanks,

    This is the code to send data from the server to the client. I think I am not closing the connection. Now I am trying to disconnect from the client side.

    Qt Code:
    1. void Server::sendData()
    2. {
    3. QByteArray block;
    4. QDataStream out(&block, QIODevice::WriteOnly);
    5. out.setVersion(QDataStream::Qt_4_0);
    6. out << (quint16)0;
    7.  
    8. QVector<double> latitude, longitude, height;
    9.  
    10. readPathData("/home/jorge/Desktop/INStest.kml", &latitude, &longitude, &height);
    11.  
    12. latitudeTest = QString::number(latitude[0]);
    13. longitudeTest = QString::number(longitude[0]);
    14. heightTest = QString::number(height[0]);
    15. positionTest.append(QString::number(latitude[0]) + " " + QString::number(longitude[0]) + " " + QString::number(height[0])+ "\n");
    16. data << positionTest[0];
    17. out << data.at(qrand() % data.size());
    18. out.device()->seek(0);
    19. out << (quint16)(block.size() - sizeof(quint16));
    20.  
    21. QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    22. clientConnection->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
    23. clientConnection->write(block);
    24. }
    To copy to clipboard, switch view to plain text mode 

Similar Threads

  1. client & server connection -Beginer
    By sathees in forum Newbie
    Replies: 1
    Last Post: 11th May 2014, 13:00
  2. Problem with TCP server/client (corrupted data)
    By chris15001900 in forum Qt Programming
    Replies: 5
    Last Post: 16th October 2011, 15:29
  3. server not getting client data
    By raj_iv in forum Qt Programming
    Replies: 0
    Last Post: 31st May 2011, 09:30
  4. Server don't receive a new request of client
    By tchoninho in forum Qt Programming
    Replies: 4
    Last Post: 27th May 2011, 09:50
  5. receive data from client via QTcpServer
    By Fallen_ in forum Qt Programming
    Replies: 4
    Last Post: 8th September 2010, 17:08

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.