TCP通信.

在“.pro”文件中添加如下语句:
QT += network
在h头文件中包含相关头文件
#include <QTcpSocket>
在头文件中添加QTcpSocket的类成员变量与函数
private:
    QTcpSocket *tcpSocket;
    void dataSend();

private slots:
    void dataReceived();
在源文件cpp添加声明:
#include <QHostAddress>
在源文件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
");
    tcpSocket->write(buf, strlen(buf));
}
原文地址:https://www.cnblogs.com/shichuan/p/4497947.html