ZC: 代码来自<<Qt及Qt Quick开发实战精解>>“代码src55-3”(“代码src55-4”里面的代码差不多,不知有何差别...貌似应该是更为完善)
ZC: 这是 Qt5 TCP客户端 简单测试类
1、TtcpClient.h
#ifndef TTCPCLIENT_H #define TTCPCLIENT_H #include <QObject> #include <QTcpSocket> class TtcpClient : public QObject { Q_OBJECT public: 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 <QDebug> #include <QHostAddress> #include <QDataStream> 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、