当前位置:网站首页>QWebsocket通信
QWebsocket通信
2022-04-22 05:44:00 【东方忘忧】
QWebsocket的使用方法和QTcpSocket特别像。
1、定义一个QWebSocketServer。
2、监听IP和端口
m_webSocketServer->listen(QHostAddress(m_ipEdit->text()),m_portEdit->text().toInt());
3、创建接收客户端的信号槽。
connect(m_webSocketServer,SIGNAL(newConnection()),this,SLOT(slotNewConnect()));
4、如果有客户端连接,则做处理,如获取socket连接,关联接收槽。
QWebSocket* socket = m_webSocketServer->nextPendingConnection();
connect(socket,&QWebSocket::disconnected,this,[=]()
{});
connect(socket,&QWebSocket::textMessageReceived,this,[=](QString text)
{});
connect(socket,&QWebSocket::binaryMessageReceived,this,[=](QByteArray array)
{};
发送文本:
socket->sendTextMessage(m_sendEdit->text());
发送二进制数据:
socket->sendBinaryMessage("IMGEND!");
发送图片:
QByteArray array;
QBuffer buffer(&array);
buffer.open(QIODevice::WriteOnly);
QPixmap pixmap(m_imgPath);
pixmap.save(&buffer,"png");
for (int i = 0; i < m_webSocketList.size() ;i++)
{
QWebSocket* socket = m_webSocketList.at(i);
QString head = "IMGSTART!|"+m_imgPath.split("/").last();
socket->sendBinaryMessage(head.toUtf8());
socket->sendBinaryMessage(array);
socket->sendBinaryMessage("IMGEND!");
}
发送文件:
m_blockSize = 64*1024;
QFileInfo fileinfo(m_filePath);
qint64 fileSize = fileinfo.size();
QString fileName = fileinfo.fileName();
QString head = QString("FILESTART!|%1#%2").arg(fileName).arg(fileSize);
QFile file(m_filePath);
file.open(QIODevice::ReadOnly);
qint64 sendSize = 0;
m_progressDialog->setRange(0,100);
m_progressDialog->setVisible(true);
qDebug() <<QStringLiteral("当前客户端:")<<m_webSocketList.size();
for (int i = 0; i < m_webSocketList.size() ;i++)
{
QWebSocket* socket = m_webSocketList.at(i);
socket->sendBinaryMessage(head.toUtf8());
QSslConfiguration config;
config.setPeerVerifyMode(QSslSocket::VerifyNone);
config.setProtocol(QSsl::AnyProtocol);
socket->setSslConfiguration(config);
qint64 writesize = fileSize;
qint64 len = 0;
do{
QByteArray array = file.read(qMin(writesize,m_blockSize));
len = socket->sendBinaryMessage(array);
sendSize += len;
writesize -= len;
//由于发送太快,增加延时防止缓冲区来不及清理造成崩溃
if (sendSize%(100*1024*1024) == 0)
{
QEventLoop eventloop;
QTimer::singleShot(1000, &eventloop, SLOT(quit()));//3000表示3000ms,即3秒,可根据实际情况修改,其他的不用变
eventloop.exec();
}
m_progressDialog->setValue(sendSize/(fileSize/100));
qDebug() <<"sendsize:"<<sendSize;
}while(writesize>0);
if(sendSize == fileSize)//检验文件信息
{
qDebug() << QStringLiteral("文件发送完毕");
socket->sendBinaryMessage("FILEEND!");
file.close();
}
}
接收数据:```接收文本
connect(socket,&QWebSocket::textMessageReceived,this,[=](QString text)
{
m_recEdit->append(QStringLiteral("接收:")+text);
if (text == "Finish")
emit signalRecFinish();
qDebug()<<"------recv1"<<text;
});
``
接收数据:```接收二进制收据
connect(socket,&QWebSocket::binaryMessageReceived,this,[=](QByteArray array){
//就收图片头部
if (array.contains("IMGSTART!"))
{
m_rectype = IMGTYPE;
m_pixName = QString(array).split("|").last();
m_arr.clear();
}
//就收图片尾部
else if (array == "IMGEND!")
{
QPixmap pixmap;
pixmap.loadFromData(m_arr);
m_imgLab->setPixmap(pixmap.scaled(m_imgLab->size(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation));
m_pixName = m_pixName.remove("bak_");
pixmap.save(QApplication::applicationDirPath()+"/"+m_pixName);
m_arr.clear();
}
//接收文件头部
else if (array.contains("FILESTART!"))
{
m_rectype = FILETYPE;
QString str = array;
str = str.split("|").last();
QString fileName = str.section("#", 0, 0);
m_fileSize = str.section("#", 1, 1).toDouble();
m_recvSize = 0;
m_file.setFileName(fileName.remove("bak_"));
//打开文件
bool isOK = m_file.open(QIODevice::WriteOnly);
if(!isOK)
{
qDebug() << QStringLiteral("打开文件失败");
}
m_progressDialog->setRange(0,100);
m_progressDialog->setVisible(true);
}
//接收文件尾部
else if (array == "FILEEND!")
{
// if(m_recvSize == m_fileSize)
// {
qDebug() << QStringLiteral("实际")<< m_fileSize;
QMessageBox::information(this, QStringLiteral("完成"), QStringLiteral("接收文件成功"));
m_file.close();
// }
}
else
{
//接收图片的二进制数据
if (m_rectype == IMGTYPE)
{
m_arr.append(array);
}
//接收文件的二进制数据
else if (m_rectype == FILETYPE)
{
qint64 len = m_file.write(array);
m_recvSize += len;
qDebug() << QStringLiteral("接收") <<m_recvSize;
m_progressDialog->setValue(m_recvSize/(m_fileSize/100));
}
}
});
版权声明
本文为[东方忘忧]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43246170/article/details/123096588
边栏推荐
- Assemble DOS interrupt function
- 常见面试问题 - 3(操作系统)
- 标准输入、标准输出、标准错误 重定向及管道
- STM32 learning note 5 - Calculation of relative position of RGB screen
- 剑指 Offer II 022. 链表中环的入口节点
- 膨胀腐蚀以及其它形态学处理
- Jeecgboot Online form Development - control Configuration
- Chapter 86 leetcode refers to offer dynamic programming (III) maximum profit of stock
- 基于51单片机和霍尔传感器的测速
- Invalid transform origin base point setting
猜你喜欢

IWDG

PyGame simple aircraft war

Experience of constructing H-bridge with MOS tube

Part 73 leetcode exercise (6) 6 Zigzag transformation

Code color difference of QT learning

Photoresist for learning of Blue Bridge Cup embedded expansion board

蓝桥杯嵌入式扩展板学习之ADC按键

LeetCode: 322. 零钱兑换(动态规划,递归,备忘录递归以及回溯)

Record one installation of centos8 + postgresql9 6 + PostGIS's painful experience

第74篇 LeetCode题目练习(七) 7.整数反转
随机推荐
Chapter 89 leetcode refers to offer dynamic programming (6) translating numbers into strings
stm32单片机与LD3320语音模块交互法二
Developing Postgres custom function with C language
常见面试题 - 4(MySQL)
IWDG
堆的基本操作源代码bing
初识数据链表
第75篇 LeetCode题目练习(八) 8.字符串转整数
STL函数库
第86篇 LeetCode剑指Offer动态规划(三)股票的最大利润
Compiling OpenSSL of arm64 on M1 chip
jeecgboot开发经验过程
Part 73 leetcode exercise (6) 6 Zigzag transformation
tcpdump的使用方法
STM32 learning note 1 - the simplest GPIO
Installing GCC on AIX and using
pygame 简单的飞机大战
jeecgboot-online在线开发3
蓝桥杯嵌入式扩展板学习之光敏电阻
PCA in scikit learn