Qt实现QTcpClient实现客户端
//初始化对象,并定义Socket读写信号处理方法
MyTcpClient::MyTcpClient(QWidget *parent) : QMainWindow(parent) { QTcpSocket tcpClient=new QTcpSocket(); tcpClient->abort(); //取消原有连接 connect(tcpClient, &QTcpSocket::readyRead,this, &MyTcpClient::ReadData); //获取数据 void (QAbstractSocket::*p)(QAbstractSocket::SocketError) =&QAbstractSocket::error; //函数指针 connect(tcpClient, p, this, &MyTcpClient::ReadError); //检测异常}
//连接server void MyTcpClient::connectServer() { tcpClient->connectToHost(“192.168.170.1”, 8951); if(tcpClient->waitForConnected(1000)) { qDebug()<<“connect success”; } else { qDebug()<<“connect fail”; }<
}
//断开连接
void MyTcpClient::disconnect() { tcpClient->disconnectFromHost(); qDebug()<<“disconnect”; }//发送数据
void MyTcpClient::sendData() { QString data=”Hello World\n”; tcpClient->write(data.toLatin1()); }//接受数据
void MyTcpClient::ReadData() { QByteArray buffer=tcpClient->readAll(); if(!buffer.isEmpty()) { qDebug()<<buffer; } }//接受异常
void MyTcpClient::ReadError(QAbstractSocket::SocketError e) { tcpClient->disconnectFromHost(); qDebug()<<“socket error: “<<e; qDebug()<<tcpClient->errorString(); }原文链接:https://blog.csdn.net/quietbxj/article/details/106575812
免责声明:文章内容来自互联网,本站不对其真实性负责,也不承担任何法律责任,如有侵权等情况,请与本站联系删除。
转载请注明出处:Qt实现QTcpClient实现客户端 https://www.yhzz.com.cn/a/14963.html