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

来源:互联网 发布:红尘网络旗舰店 编辑:程序博客网 时间:2024/05/16 06:39

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 0