QT Tcp客户端发送接收并存初体验随笔

VS2010

习惯于VS2010的开发,tcp客户端链接后,习惯性创建发送和接收线程来达到并行处理发送接收数据

QT

也可以创建收发线程进行数据处理,不过不能将socket以指针方式进行或全局方式在线程中使用,需要依赖socketDescriptor操作,不过在windows下,利用网口调试助手测试收发的总字节数对不上号,不知道为什么,可能是才疏学浅,亦或是windows下不能这么用,总之跳过,主要记录利用信号与槽方式进行客户端收发

QT版本

qt-opensource-windows-x86-msvc2010_opengl-5.4.1.exe

包含头文件

#include <QTcpSocket>
#include <QByteArray>

源文件处理

初始构建

 m_pClient = new QTcpSocket(this);
 if (m_pClient)
 {
  connect(m_pClient, SIGNAL(readyRead()), this, SLOT(recvSlot()));  // 查阅资料即可知道
  connect(m_pClient, SIGNAL(bytesWritten(qint64)), this, SLOT(sendSlot(qint64)));  // 关键,能够在接收数据同时,能够连续发送数据的关键
 }

连接服务端

  m_pClient->abort();
 m_pClient->connectToHost(strIP, port);
 const int timeOut = 5 * 1000;
 if (!m_pClient->waitForConnected(timeOut))
 {
 
 }
 else
 { 
  
 }

接收槽函数

void TcpClient::recvSlot()
{
 QByteArray dat = m_pClient->readAll();
}


发送以及发送槽函数

发送函数
void TcpClient::send(const quint64& sendDatLen, const unsigned int& cnt)
{
 if (m_bConnect)
 {
  m_sendDat = increasingSequence(sendDatLen);
  m_totalBytes = sendDatLen*cnt;
  m_bytesToWrite = m_totalBytes - m_pClient->write(m_sendDat);
 }
}

QByteArray TcpClient::increasingSequence(const quint64& sendDatLen)
{
 QByteArray tmp;
 unsigned char cnt = 0x0;
 while (tmp.length() < sendDatLen)
 {
  tmp.append(cnt++);
 }
 return tmp;
}

发送槽函数
void TcpClient::sendSlot(qint64 numBytes)
{
 m_bytesWritten += numBytes;
 if (m_bytesToWrite > 0)
 {
  m_bytesToWrite -= m_pClient->write(m_sendDat);
 }
 else
 {
  if (m_bytesWritten == m_totalBytes)
  {
  }
 }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值