QTcpSocket:向QTcpServer发送可靠数据:检测未插入的电缆

时间:2014-03-07 15:32:17

标签: qt sockets tcp

我必须使用QTcpSocket将数据从使用QTcpSocket的服务器发送到使用QTcpServer的服务器。 连接建立一次,数据逐行发送,终止符为“\ r \ n”(服务器在此终结器上分割传入数据)

如果需要知道哪条线路可以成功,哪条线路不成功。

这可以按预期工作。但是,如果我从网络上拔下服务器网络电缆,客户端仍在写入数据,并且仍然会发出“bytesWritten”信号。

但没有发生写入错误,并且未发出“错误”信号。即使TPC连接丢失,QTcpSocket似乎也在将数据写入内部缓冲区。使用flush()无效。

基于财富客户的示例代码:

Client::Client(QWidget *parent)
  :   QDialog(parent), networkSession(0)
{

  m_messageCount=0;
  QString ipAddress= "192.168.1.16"; 


  m_socket = new QTcpSocket(this);
  //No effect...
  //m_socket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);


  connect(m_socket, SIGNAL(connected()), this, SLOT(Connected()));
  connect(m_socket, SIGNAL(disconnected()), this, SLOT(DisConnected()));
  connect(m_socket, SIGNAL(bytesWritten(qint64)), this, SLOT(OnBytesWritten(qint64)));
  connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)),    this, SLOT(displayError(QAbstractSocket::SocketError)));

}

void Client::connectToHost()
{
  m_socket->connectToHost("192.168.1.16", 1234);
}

void Client::Connected()
{
  qDebug() << "Connected()";
  QTimer::singleShot(1000, this, SLOT(SendNextRecord()));
}

void Client::DisConnected()
{
  qDebug() << "DisConnected()";
}

void Client::SendNextRecord()
{
  m_messageCount++;

  QByteArray singleRecord=QString("Nr: %1 Some Text").arg(m_messageCount).toUtf8();
  singleRecord.append("\r\n");

  Q_ASSERT(m_socket->isValid());
  qDebug() << "Sending: " <<singleRecord;

  //bytesSend always > 0
  qint64 bytesSend=m_socket->write(singleRecord);

  //No effect
  m_socket->flush();
  qDebug() <<"bytes Send:" << bytesSend;
}

//Signal is still emitted even if network cable is unplugged 
void Client::OnBytesWritten(qint64 bytes)
{
  qDebug() << "OnBytesWritten:" << bytes; 

  //No effect
  m_socket->flush();
  QTimer::singleShot(1000, this, SLOT(SendNextRecord()));
}

//Signal not emitted even if network cable is unplugged
void Client::displayError(QAbstractSocket::SocketError socketError)
{
   qDebug() << "Socket error";
}

我可以更改此行为吗?

0 个答案:

没有答案