接上几篇关于websocket的内容,给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 = file.readAll();
WebSocket->sendBinaryMessage(byte);//发送二进制消息
file.close();
发送文件之前先发送文件名称,发送原理是文件转成二进制流再发送
服务端处理:
void Widget::ReceivedMsg(const QString &message)
{
QJsonDocument jsonDocument = QJsonDocument::fromJson(message.toLatin1().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)
{
QWebSocket * webSocket = qobject_cast<QWebSocket *>(sender());
QFile file(receiverFileName);
file.open(QFile::WriteOnly);
file.write(message);
file.close();
ui->textEdit->append("收到来自" + webSocket->origin() + "的文件:" + receiverFileName);
}