【QT网络-TCP】双端数据收发,QTcpSocket客户端数据接收并写入到文件中,能在PC和Ubuntu、Ubuntu和开发板之间通信
一、【客户端】Widget构造函数中连接信号槽
connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(receiveMessages()));
二、【客户端】槽函数完成数据接收、显示、写入到文件
void Widget::receiveMessages()
{
//先存储下来,为tcpSocket->readAll()只能用一次,再次调用是返回空
QByteArray tmpByteArray = tcpSocket->readAll();
fileContent.append(" " + tmpByteArray);
//接受消息并显示
ui->textBrowser->append("服务端:" + tmpByteArray);
//QString fileName = QFileDialog::getOpenFileName(this, "选择文本", "/home/zyl"); //返回的是一个字符串(路径+文件名)
//qDebug() << fileName << endl;
//设置要打开的文件
//file.setFileName(fileName);
//将数据写入到本地文件
QFile file("/home/zyl/test.txt.txt");
//打开文件
if(!file.open(QIODevice::ReadWrite)){
//文件打开失败
qDebug() << "文件打开失败" << endl;
return;
}
//写文件 file.write是将写入的内容覆盖到文本内,如原文本内容为22222,写入111,结果文本内容为11122
file.write(fileContent);
qDebug() << tmpByteArray << endl;
//关闭文件
file.close();
}
三、传输数据界面展示
图1 服务端界面
图2 客户端界面
图3 文本内容