简体   繁体   中英

socket server could not receive the message send by client

I use Qt creator 5.5.1 in windows 7.

The complier is VC 2010 32Bits.

I have written a socket client. It could connect well but the message could not be sent to the server.

No error occurs when I debug the program.

char flash_result_data[] ={'0', '0', '0', '0', '0', '0', '0', '0'};


void MainWindow::on_pushBtn_LoadCfg_clicked()
{


 if (tcpClient == NULL)                     
 {
    tcpClient = new QTcpSocket;
    tcpClient->connectToHost(ui->txtIPServer->text(),ui->txtPortServer->text().toInt());

    Sleep(1000);
    QObject::connect(tcpClient,SIGNAL(readyRead()),this, SLOT(readMessageFromTCPServer()));
    QTimer::singleShot(100000, this, SLOT(fun_timer()));
  }  
}
void MainWindow::readMessageFromTCPServer()
{
  QObject::connect(this, SIGNAL( MySignal() ),this, SLOT( MySlot() ) );



  std::string r="start";

  QByteArray qba;

  qba= tcpClient->readAll();
  if (qba.contains(r.c_str()))
  {
    emit MySignal();
  }
  return;

}
void MainWindow::fun_timer()
{

  int flash_result_data_size = sizeof(flash_result_data) / sizeof(char);
  std::string  flash_result_data_str = convertToString(flash_result_data, flash_result_data_size);
  tcpClient->write(flash_result_data_str.c_str(),strlen((flash_result_data_str.c_str())));

}

When I debug the program, the socket could connect well. And after run this line: tcpClient->write(flash_result_data_str.c_str(),strlen((flash_result_data_str.c_str()))); , no error occurs, but there is no message received from socket server.

The socket server is developed by others and is used many times in other similar project so the server must be OK. The problem is my client code. But I do not know where my error is.

At the top of the file add #include<QDebug> .

In MainWindow class header file, add QByteArray qba; as a private member variable.

Change your readMessageFromTCPServer to:

void MainWindow::readMessageFromTCPServer()
{
  QObject::connect(this, SIGNAL( MySignal() ),this, SLOT( MySlot() ) );


  std::string r="start";

  qba.append(tcpClient->readAll());
  qDebug() << "BUFFER:" << QString::fromUtf8(qba);

  if (qba.contains(r.c_str()))
  {
    emit MySignal();
  }
  return;

}

Look at qDebug output to see how the data is being received. Also, I think this connection is not necessary QObject::connect(this, SIGNAL( MySignal() ),this, SLOT( MySlot() ) ); .

You could just call MySlot(); since both the signal and the slot are part of the same object.

if (qba.contains(r.c_str()))
  {
    MySlot();
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM