Results 1 to 2 of 2

Thread: QTcpsocket Problem - unable to read written data to socket

  1. #1
    Join Date
    Oct 2010
    Posts
    2
    Qt products
    Qt4
    Platforms
    Unix/X11

    Default QTcpsocket Problem - unable to read written data to socket

    hello there ,

    I am writing an accounting open source project for my course.it is finished but by no means I can transfer data between client and server.the qdebug days the data is written to the socket but on the other side I can not read that.I put all the codes in files in the attachments.
    the code is small but is very important to me.
    even if you do not have time you can look the code and suggest a better way of writing the client/multi threaded server.
    most of the code is copied from fortune server/client.
    you can make it using qmake

    Thank you in advance
    Attached Files Attached Files

  2. #2
    Join Date
    Oct 2010
    Posts
    2
    Qt products
    Qt4
    Platforms
    Unix/X11

    Default Re: QTcpsocket Problem - unable to read written data to socket

    and here are some parts of the code in case you do not want to open the file.

    this will be the client

    Qt Code:
    1. FreeCafe_Client::FreeCafe_Client()
    2. :QWidget(), currentState(Disconnected)
    3. {
    4. qDebug("FreeCafe_Client::FreeCafe_Client");
    5. setAttribute(Qt::WA_DeleteOnClose);
    6. // setWindowFlags(Qt::WindowStaysOnTopHint);
    7. // setWindowState(Qt::WindowFullScreen);
    8. resize(QApplication::desktop()->screenGeometry().size());
    9. settings = new QSettings("FSF", "FreeCafe", this);
    10. createUi();
    11. socket = new QTcpSocket(this);
    12. connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
    13. SLOT(slotStateChanged(QAbstractSocket::SocketState)) );
    14. connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
    15. SLOT(slotError(QAbstractSocket::SocketError)));
    16. connect(socket, SIGNAL(readyRead()),this,
    17. SLOT(slotReadyRead()));
    18. connect(socket, SIGNAL(connected()),SLOT(authorize()));
    19.  
    20. QNetworkConfigurationManager manager;
    21. if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
    22. // Get saved network configuration
    23. QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
    24. settings.beginGroup(QLatin1String("QtNetwork"));
    25. const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
    26. settings.endGroup();
    27.  
    28. // If the saved network configuration is not currently discovered use the system default
    29. QNetworkConfiguration config = manager.configurationFromIdentifier(id);
    30. if ((config.state() & QNetworkConfiguration::Discovered) !=
    31. QNetworkConfiguration::Discovered) {
    32. config = manager.defaultConfiguration();
    33. }
    34.  
    35. networkSession = new QNetworkSession(config, this);
    36. connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));
    37.  
    38. qDebug("Opening network session.");
    39. networkSession->open();
    40. }
    41. }
    42.  
    43. FreeCafe_Client::~FreeCafe_Client()
    44. {}
    45.  
    46. void FreeCafe_Client::createUi()
    47. {
    48. qDebug("FreeCafe_Client::createUi");
    49. QWidget *wd = new QWidget(this);
    50. ui.setupUi(wd);
    51. QHBoxLayout *h = new QHBoxLayout(this);
    52. // h->addSpacerItem(new QSpacerItem(40, 40));//, QSizePolicy::MinimumExpanding));
    53. h->addWidget(wd);
    54. // h->addSpacerItem(new QSpacerItem(40, 40));//, QSizePolicy::MinimumExpanding));
    55. connect(ui.btnLogin, SIGNAL(clicked()), SLOT(login()));
    56. ui.server->setText(settings->value("lastHostIP", QString("127.0.0.1")).toString());
    57. }
    58.  
    59. void FreeCafe_Client::login()
    60. {
    61. qDebug("FreeCafe_Client::login");
    62. socket->abort();
    63. QString host;
    64. if(ui.server->text().isEmpty())
    65. host = HOST;
    66. else
    67. host = ui.server->text();
    68. socket->connectToHost(host, PORT);
    69. settings->setValue("lastHostIP", ui.server->text());
    70. }
    71.  
    72. void FreeCafe_Client::slotStateChanged(QAbstractSocket::SocketState newState)
    73. {
    74. qDebug()<<"FreeCafe_Client::slotStateChanged: "<<newState;
    75. if (newState == QAbstractSocket::ConnectedState)
    76. { authorize(); }
    77. }
    78.  
    79. void FreeCafe_Client::authorize()
    80. {
    81. qDebug("FreeCafe_Client::authorize");
    82. currentState = Connecting;
    83. QByteArray data;
    84. QByteArray block;
    85.  
    86. data = block = ui.username->text().toAscii() + ':' + ui.password->text().toAscii();
    87. QDataStream out(&block, QIODevice::WriteOnly);
    88.  
    89. out.setVersion(QDataStream::Qt_4_0);
    90. out << data;
    91. socket->write(block);
    92. qDebug()<<"Data sent to server: "<<data<<" size: "<<socket->write(block);
    93.  
    94. // socket->waitForReadyRead();//I think we can use this function and continue the process here, Instead of using the signal and FreeCafe_Client::slotReadyRead()
    95.  
    96. }
    97.  
    98. void FreeCafe_Client::slotError(QAbstractSocket::SocketError socketError)
    99. {
    100. qDebug()<<"FreeCafe_Client::slotError"<< socketError;
    101. }
    102.  
    103. void FreeCafe_Client::slotReadyRead()
    104. {
    105. qDebug("FreeCafe_Client::slotReadyRead");
    106. if(currentState == Connecting){
    107. bool ok;
    108. QByteArray data = socket->readAll();
    109. int res = data.toInt(&ok);
    110. qDebug()<< QString::number(res);
    111. if(ok){
    112. if(res == -1){
    113. QMessageBox::critical(this, tr("Wrong username/password"),
    114. tr("username or password is wrong."));
    115. } else if(res == 0){
    116. QMessageBox::critical(this, tr("No credit"),
    117. tr("You do not have enough credit to use this service."));
    118. } else {
    119. MainWindow *f = new MainWindow(res, this->socket, this->networkSession);
    120. f->show();
    121. close();
    122. }
    123. } else {
    124. qDebug()<<"Malformed response: "<<data;
    125. QMessageBox::critical(this, tr("Malformed response"),
    126. tr("The data returned from server is not valid."));
    127. }
    128.  
    129. } else if (currentState == Disconnected) {
    130.  
    131. QDataStream in(socket);
    132. in.setVersion(QDataStream::Qt_4_0);
    133.  
    134. qDebug()<<"FreeCafe_Client::slotReadyRead: currentState==Disconnected: "<<socket->bytesAvailable();
    135.  
    136. QString data;
    137. in >> data;
    138. qDebug()<<"FreeCafe_Client::slotReadyRead: "<<data;
    139. if(data == "OK"){
    140. authorize();
    141. }
    142. }
    143. }
    144.  
    145. void FreeCafe_Client::sessionOpened()
    146. {
    147. qDebug("FreeCafe_Client::sessionOpened");
    148. // Save the used configuration
    149. QNetworkConfiguration config = networkSession->configuration();
    150. QString id;
    151. if (config.type() == QNetworkConfiguration::UserChoice)
    152. id = networkSession->sessionProperty(QLatin1String("UserChoiceConfiguration")).toString();
    153. else
    154. id = config.identifier();
    155.  
    156. QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
    157. settings.beginGroup(QLatin1String("QtNetwork"));
    158. settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id);
    159. settings.endGroup();
    160. }
    To copy to clipboard, switch view to plain text mode 

    and this will do the server,although it is a thread only.

    Qt Code:
    1. CafeThread::CafeThread(int sDescriptor, QObject *parent) :
    2. QThread(parent), socketDescriptor(sDescriptor), isConnectedToClient(false)
    3. {
    4. }
    5.  
    6. void CafeThread::run()
    7. {
    8. qDebug("CafeThread::run");
    9. socket = new QTcpSocket;
    10. if( !socket->setSocketDescriptor(socketDescriptor) ) {
    11. emit error(socket->error());
    12. qDebug()<<"CafeThread::run: ERROR: "<<socket->errorString();
    13. return;
    14. }
    15. connect(socket, SIGNAL(readyRead()),this, SLOT(slotReadyRead()));
    16. connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
    17. SLOT(slotStateChanged(QAbstractSocket::SocketState)));
    18. connect(this , SIGNAL(logintimer()), SLOT(slottimerstart()));
    19. connect(&timer, SIGNAL(timeout()), SLOT(slotOneMinutePassed()));
    20.  
    21. QByteArray block;//This was for test
    22. QDataStream out(&block, QIODevice::WriteOnly);
    23. out.setVersion(QDataStream::Qt_4_0);
    24. out << "OK";
    25. qDebug()<<"CafeThread::run: Data sent from server: 'OK' size: "<<socket->write(block);
    26. QByteArray data = socket->readAll();
    27. qDebug()<<"CafeThread::slotReadyRead: data recieved:"<<data;
    28. //QDataStream in(socket);
    29. socket->write(block);//
    30. }
    31.  
    32. void CafeThread::slotReadyRead()
    33. {
    34. qDebug("CafeThread::slotReadyRead");
    35. QByteArray data = socket->readAll();
    36. qDebug()<<"CafeThread::slotReadyRead: data recieved:"<<data;
    37. QString credentials = QString::fromAscii(data);
    38. QStringList userpass = credentials.split(':');
    39. int credit = -1;
    40. if(userpass.count() == 2){
    41. qDebug("User/pass recieved from client");
    42. QString username = userpass[0];
    43. QString password = userpass[1];
    44. this->user = username;
    45. q.prepare("SELECT Name, password, credit FROM users WHERE Name=? AND password=?");
    46. q.addBindValue(username);
    47. q.addBindValue(password);
    48. if(q.next()){
    49. credit = q.value(2).toInt();
    50. this->money = credit;
    51. if(credit > 100){//User cannot login when its credit is less than 100
    52. isConnectedToClient = true;
    53. emit loggedIn(username, credit);
    54. emit logintimer();
    55. // char *tt = credit;//how should I convert this ? ERROR HERE
    56. //socket->write(&credit,sizeof(credit));// DATA CAN NOT BE PUSHED TO CLIENT
    57. }
    58. } else {
    59. credit = -1;
    60. }
    61. if(socket->write(QByteArray::number(credit)) == -1){
    62. qDebug()<<socket->errorString();
    63. }
    64. }
    65. if(credit < 10)
    66. socket->close();
    67. }
    68.  
    69. void CafeThread::slotStateChanged(QAbstractSocket::SocketState newState)
    70. {
    71. qDebug()<< newState;
    72. switch(newState){
    73. case QAbstractSocket::ClosingState:
    74. if(isConnectedToClient){
    75. emit loggedOut(this->user, this->usedtime);
    76. quit();
    77. }
    78. break;
    79. case QAbstractSocket::UnconnectedState:
    80. case QAbstractSocket::HostLookupState:
    81. case QAbstractSocket::ConnectedState:dosomething();break;
    82. case QAbstractSocket::ConnectingState:
    83. case QAbstractSocket::BoundState:
    84. case QAbstractSocket::ListeningState:
    85. default:
    86. break;
    87. }
    88. }
    To copy to clipboard, switch view to plain text mode 

    I have removed parts which are not concerned !

Similar Threads

  1. QTcpSocket read duplicate data, but only on "bad channel"
    By creatron in forum Qt Programming
    Replies: 1
    Last Post: 24th May 2010, 19:17
  2. Replies: 1
    Last Post: 24th March 2010, 08:15
  3. Problem in printing the data return /read from QTcpsocket
    By skumar434 in forum Qt Programming
    Replies: 3
    Last Post: 20th February 2009, 19:36
  4. Unable to read from QTcpSocket
    By jimroos in forum Qt Programming
    Replies: 1
    Last Post: 4th July 2007, 21:09
  5. Replies: 3
    Last Post: 4th July 2006, 10:15

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.