ZC: 代码来自<<Qt及Qt Quick开发实战精解>>“代码\src\5\5-3”(“代码\src\5\5-4”里面的代码差不多,不知有何差别...貌似应该是更为完善)
ZC: 这是 Qt5 TCP客户端 简单测试类
1、TtcpClient.h
#ifndef TTCPCLIENT_H#define TTCPCLIENT_H#include#include class TtcpClient : public QObject{ Q_OBJECTpublic: explicit TtcpClient(QObject *parent = 0);signals:public slots:public: QTcpSocket *FsktTcp;public: void NewConnectZ(QString _strDestIP, qint16 _iDestPort);// 创建新连接 void AbortZ();// 取消 void CloseZ();// 关闭 // *** void WriteZ();// 发送数据public slots: void ReadyReadZ();// 读取数据 void SocketErrorZ(QAbstractSocket::SocketError _socketError);// 错误处理};#endif // TTCPCLIENT_H
2、TtcpClient.cpp
#include "TtcpClient.h"#include#include #include TtcpClient::TtcpClient(QObject *parent) : QObject(parent){ FsktTcp = new QTcpSocket(this); // 错误处理 connect(FsktTcp, SIGNAL(QAbstractSocket::error(SocketError)), this, SLOT(SocketErrorZ(QAbstractSocket::SocketError))); // 读取数据 connect(FsktTcp, SIGNAL(readyRead()), this, SLOT(ReadyReadZ()));}// 创建新连接void TtcpClient::NewConnectZ(QString _strDestIP, qint16 _iDestPort){ FsktTcp->abort(); QHostAddress ha(_strDestIP); FsktTcp->connectToHost(ha, _iDestPort);}// 取消void TtcpClient::AbortZ(){ FsktTcp->abort();}// 关闭void TtcpClient::CloseZ(){ FsktTcp->close();}// 错误处理void TtcpClient::SocketErrorZ(QAbstractSocket::SocketError _socketError){ switch(_socketError) { case QAbstractSocket::RemoteHostClosedError : { qDebug() << "Remote host closed ."; break; } default : qDebug() << FsktTcp->errorString(); }}// 读取数据void TtcpClient::ReadyReadZ(){ QDataStream in(FsktTcp); in.setVersion(QDataStream::Qt_5_5); QByteArray baRead = FsktTcp->readAll(); qDebug() << QString::fromLocal8Bit(baRead);// 接收完毕,就关闭socket}// 发送数据void TtcpClient::WriteZ(){ QByteArray outBlock; outBlock = outBlock.append("test out"); QDataStream out(&outBlock, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_5_5); //qDebug() << outBlock.size(); //out. // 发送数据 FsktTcp->write(outBlock);}
3、