当前位置:网站首页>Qwebsocket communication
Qwebsocket communication
2022-04-23 05:28:00 【Oriental forgetfulness】
QWebsocket How to use and QTcpSocket Special like .
1、 Define a QWebSocketServer.
2、 monitor IP And port
m_webSocketServer->listen(QHostAddress(m_ipEdit->text()),m_portEdit->text().toInt());
3、 Create a signal slot to receive the client .
connect(m_webSocketServer,SIGNAL(newConnection()),this,SLOT(slotNewConnect()));
4、 If there is a client connection , Then deal with , If you get socket Connect , Associated receiving slot .
QWebSocket* socket = m_webSocketServer->nextPendingConnection();
connect(socket,&QWebSocket::disconnected,this,[=]()
{});
connect(socket,&QWebSocket::textMessageReceived,this,[=](QString text)
{});
connect(socket,&QWebSocket::binaryMessageReceived,this,[=](QByteArray array)
{};
Send text :
socket->sendTextMessage(m_sendEdit->text());
Send binary data :
socket->sendBinaryMessage("IMGEND!");
Send pictures :
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!");
}
Send a file :
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(" Current client :")<<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;
// Due to sending too fast , Increase the delay to prevent the buffer from crashing before it has time to clean up
if (sendSize%(100*1024*1024) == 0)
{
QEventLoop eventloop;
QTimer::singleShot(1000, &eventloop, SLOT(quit()));//3000 Express 3000ms, namely 3 second , It can be modified according to the actual situation , The others don't change
eventloop.exec();
}
m_progressDialog->setValue(sendSize/(fileSize/100));
qDebug() <<"sendsize:"<<sendSize;
}while(writesize>0);
if(sendSize == fileSize)// Inspection document information
{
qDebug() << QStringLiteral(" The file has been sent ");
socket->sendBinaryMessage("FILEEND!");
file.close();
}
}
receive data :``` Receive text
connect(socket,&QWebSocket::textMessageReceived,this,[=](QString text)
{
m_recEdit->append(QStringLiteral(" receive :")+text);
if (text == "Finish")
emit signalRecFinish();
qDebug()<<"------recv1"<<text;
});
``
receive data :``` Receive binary receipt
connect(socket,&QWebSocket::binaryMessageReceived,this,[=](QByteArray array){
// Just take the picture head
if (array.contains("IMGSTART!"))
{
m_rectype = IMGTYPE;
m_pixName = QString(array).split("|").last();
m_arr.clear();
}
// Just close the end of the picture
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();
}
// Receive file header
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_"));
// Open file
bool isOK = m_file.open(QIODevice::WriteOnly);
if(!isOK)
{
qDebug() << QStringLiteral(" fail to open file ");
}
m_progressDialog->setRange(0,100);
m_progressDialog->setVisible(true);
}
// Receive the end of the file
else if (array == "FILEEND!")
{
// if(m_recvSize == m_fileSize)
// {
qDebug() << QStringLiteral(" actual ")<< m_fileSize;
QMessageBox::information(this, QStringLiteral(" complete "), QStringLiteral(" File received successfully "));
m_file.close();
// }
}
else
{
// Receive binary data of pictures
if (m_rectype == IMGTYPE)
{
m_arr.append(array);
}
// Receive binary data of the file
else if (m_rectype == FILETYPE)
{
qint64 len = m_file.write(array);
m_recvSize += len;
qDebug() << QStringLiteral(" receive ") <<m_recvSize;
m_progressDialog->setValue(m_recvSize/(m_fileSize/100));
}
}
});
版权声明
本文为[Oriental forgetfulness]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220543306971.html
边栏推荐
- Three of three JS (webgl) is simple to draw lines / arcs according to points (based on linegeometry / line2 / linematerial, draw two arc segments based on the center of the circle)
- Create process memory management copy_ Mm - processes and threads (IX)
- Ehcache Memcache redis three caches
- d.ts---更详细的知识还是需要看官网的介绍(声明文件章节)
- Use of ES6 array
- Redis的基本知识
- Box collapse and margin collapse
- CPT 104_ TTL 09
- Necessity of selenium preloading cookies
- 相机成像+单应性变换+相机标定+立体校正
猜你喜欢

Various situations of data / component binding

Double click The jar package cannot run the solution

selenium預先加載cookie的必要性

Low code and no code considerations

Laravel routing job

相机成像+单应性变换+相机标定+立体校正

Top 25 Devops tools in 2021 (Part 2)

Create a tabbar component under the components folder, which is public

What are the most popular recruitment technical skills in 2022? You can't think of it

2021-10-12
随机推荐
Excel 2016 cannot open the file for the first time. Sometimes it is blank and sometimes it is very slow. You have to open it for the second time
Ehcache Memcache redis three caches
es6数组的使用
String class understanding - final is immutable
弘玑微课堂 | Cyclone RPA之“灵活的数字员工”执行器
STL learning notes 0x0001 (container classification)
Multiple mainstream SQL queries only take the latest one of the data
Arithmetic and logical operations
Create cells through JS (while loop)
Open source rule engine - Ice: dedicated to solving flexible and complex hard coding problems
If I am PM's performance, movie VR ticket purchase display
WTL 自绘控件库 (CQsCheckComboxBox)
Simple and basic use of switch and if
Quick app bottom navigation bar
Camera imaging + homography transformation + camera calibration + stereo correction
How to add beautiful code blocks in word | a very complete method to sort out and compare
CORS and proxy (づ  ̄ 3  ̄) in egg ~ the process of stepping on the pit and filling the pit ~ tot~
Traversal array, object parent-child communication props / $emit
Kanban Quick Start Guide
How to realize adaptive layout