在“.pro”文件中添加如下语句:QT += network在h头文件中包含相关头文件#include在头文件中添加QTcpSocket的类成员变量与函数private: QTcpSocket *tcpSocket; void dataSend();private slots: void dataReceived();
在源文件cpp添加声明:#include在源文件cpp文件构造函数中添加如下语句: tcpSocket = new QTcpSocket(this); connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(dataReceived())); QHostAddress *serverIP = new QHostAddress(); serverIP->setAddress("192.168.1.254"); tcpSocket->connectToHost(*serverIP , 8080); delete serverIP;
在源文件cpp添加dataReceived()槽函数的实现代码void Widget::dataReceived(){ char buf[1024]; while(tcpSocket->bytesAvailable() > 0) { memset(buf, 0, sizeof(buf)); tcpSocket->read(buf, sizeof(buf)); QMessageBox::information(this, tr("data"), buf); }}
在源文件cpp添加发送TCP数据的实现代码void Widget::dataSend(){ char buf[1024]; memset(buf, 0, sizeof(buf)); strcpy(buf, "hello world\n"); tcpSocket->write(buf, strlen(buf));}
翻译结果