Qt demo, 做了一个Tcp发送的例子,参考:https://stackoverflow.com/questions/7923485/simplest-qt-tcp-client

代码如下:

1. 引用与全局socket定义:

#include <QTcpSocket>

QTcpSocket *socket;

2. 发送与接收

//发送
void FormNetComm::writeTCP(){
    QString msg = "ABC-123";
    QByteArray bytes = msg.toUtf8();
    socket = new QTcpSocket(this); 
    connect( socket, SIGNAL(readyRead()), SLOT(readTCP()) );
    socket->connectToHost("127.0.0.1", 1000);
    if(socket->waitForConnected()) {
       socket->write(bytes);
    }
}

//接收
void FormNetComm::readTCP()
{
    QByteArray data = socket->readAll();
    QString str = QString::fromUtf8(data);
    qDebug() << "response: " << str;
}

效果,TCP助手、QtCreator输出:

Qt TCP发送与接收_QT教程         Qt TCP发送与接收_QT开发_02