Qt⽹络编程:QWebSocket发送⽂件接上⼏篇关于websocket的内容,给加上发送⽂件功能
if(!WebSocket)
return;
QString path = QFileDialog::getOpenFileName(this,
QString("打开⽂件"),
"/",
QString("Image File(*.* *.jpg *.jpeg *.png *.txt *.avi *.mp4)"));
if(path.isEmpty())
return;
QFileInfo info(path);
QString file_name = info.fileName();
WebSocket->sendTextMessage("sendFileStart:" + file_name);
QFile file(path);
if(!file.open(QIODevice::ReadOnly))
{
return;
}
QByteArray byte = adAll();
WebSocket->sendBinaryMessage(byte);//发送⼆进制消息
file.close();
发送⽂件之前先发送⽂件名称,发送原理是⽂件转成⼆进制流再发送
处理:
void Widget::ReceivedMsg(const QString &message)
{
QJsonDocument jsonDocument = QJsonDocument::Latin1().data());
if(jsonDocument.isNull() )
{
QWebSocket * webSocket = qobject_cast<QWebSocket *>(sender());
if(message.startsWith("sendFile"))
{
receiverFileName = message.split(":").at(1);
}
else
{
ui->textEdit->append("收到消息:" + webSocket->origin() + " - " + message);
}
}
else
{
QJsonObject obj = jsonDocument.object();
QString dst = obj["dst"].toString();
for (auto socket:webSocketList)
{
if(dst == socket->origin())
socket->sendTextMessage(message);
}
}
}
connect(webSocket,&QWebSocket::textMessageReceived,this,&Widget::ReceivedMsg);
void Widget::onBinaryMessageReceived(const QByteArray &message)
{
websocket和socketQWebSocket * webSocket = qobject_cast<QWebSocket *>(sender());
QFile file(receiverFileName);
file.open(QFile::WriteOnly);
file.write(message);
file.close();
ui->textEdit->append("收到来⾃" + webSocket->origin() + "的⽂件:" + receiverFileName); }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论