Basic computer protocols/concepts: Push data - WebSocket and SSE; Front-end Blob/URL download files

Basic computer protocols/concepts: Pushing data—WebSocket and SSE

1 WebSocket: two-way communication

1.1 Concept: Communication Process

Insert image description here

①Upgrade: The browser tells the server to upgrade to the WebSocket protocol
②Switch: After the server is upgraded successfully, a 101 status code will be returned.
③Communicate: The browser and server can send data in WebSocket format

1.2 Practical combat: Implementing a simple chat room

WebSocket in action: implementing a simple chat room

2 SSE (Server Send Event): Server single push message, text/event-stream

Insert image description here

2.1 Concept: Characteristics

①Content-Type returned by the server: text/event-stream

This is a stream that can return content multiple times

  • Server Send Event uses this kind of message to push data at any time.

Insert image description here

2.2 Application scenarios

① CICD platform prints logs in real time

The CICD platform needs to print logs in real time, so how does its log achieve real-time printing?

  • This obviously requires data to be transmitted piece by piece, and generally SSE is used to push the data.
②ChatGPT answer box: Load answers part by part

ChatGPT’s answers are not given all at once, but are loaded part by part.

Insert image description here

Expansion: Front-end file downloading methods Blob downloading and URL downloading

  • Blob downloading is suitable for scenarios where file content needs to be dynamically generated, such as exporting data generated by the front end into files, such as exporting Excel, exporting PDF, etc.
  • Browser URL direct download is suitable for downloading files that already exist on the server, such as users downloading software installation packages, downloading pictures, downloading documents, etc.

1. Load URL (location.href): You can download files that cannot be previewed by the browser (.tar, etc.)

For files that cannot be opened by the browser (for example: .rar, .doc, etc.), file downloading can be implemented, but for files that can be opened by the browser (for example: .txt, .xml, etc.), only the preview function can be implemented

  • location.href
  • window.open
  • a tag
window.location.href="https://106.14.15.103:8000/downloadFile/test"

The above three methods are all downloaded directly by loading the file URL. If the backend returns the file stream, it needs to be converted into a URL before downloading.
In addition, the above three methods default to the get method. If you need to use the post method and need to pass parameters, it is best to Use the following file stream method

2. File stream download (the backend returns the file stream and converts it to blob)

Now there is a requirement for file downloading, but authentication is required, which means that you cannot download by returning the download link in the background, because once someone else gets this link, you can download it directly without any permission, so you need To change the way of thinking, then you need to use blob (binary large object) object, which is the following method

1. Ajax request to download the file stream
2. Convert the downloaded file stream into blob data
3. Convert the blob into url through window.URL.createObjectURL(blob)
4. Simulate click event download by dynamically generating a tag

Blob usage scenarios:

  • Upload large files in parts
this.$http({
    
    
   url: this.$http.adornUrl(`/strUrl/${
      
      id}`),
   method: 'get',
   responseType: 'blob',
   timeout: 1000 * 600
 }).then(res => {
    
    
   console.log('res', res)
   if (res.status === 200) {
    
    
     const blob = new Blob([res.data], {
    
     type: `application/octet-stream` })
     const downloadElement = document.createElement('a')
     const href = window.URL.createObjectURL(blob)
     downloadElement.href = href
     downloadElement.download = `${
      
      filename}`
     downloadElement.click()
   } else {
    
    
     this.$message.error('下载出错!')
   }
 })

A Blob object represents an immutable, raw data file-like object. Its data can be read in text or binary format, or converted into a ReadableStream for data operations.

3. The difference between the two

  1. Returning a URL: When the backend returns a URL, it actually stores the file on the server and returns the file's URL to the frontend. The front end downloads the file by accessing this URL. This approach requires ensuring that file access permissions on the server are set correctly to prevent unauthorized users from accessing files.
  2. Return binary stream: When the backend directly returns the binary stream, the frontend can save the binary data as a Blob object and save the file locally through Blob download. This method does not require files to be stored on the server and can dynamically generate file contents. For some sensitive data, storage on the server can be avoided.
  • Compared to returning URLs, Blob downloads have the following advantages, providing greater security:
  • Avoid storing sensitive data on the server: Using blob downloads can avoid storing sensitive data on the server, reducing the risk of data leakage.
  • Dynamically generate file content: Blob downloads can dynamically generate file content, which means that non-file type data (such as charts, reports, etc.) can be directly generated as files for download without the need for the file to exist on the server in advance.
  • Temporary: Blob objects are temporary and only exist in the browser's memory and will not be saved locally permanently. This reduces the risk of your files being maliciously obtained by others.
3.1 URL: static file download, file sharing

Return URL usage scenario:

Static file download: suitable for accessing and downloading static files that already exist on the server, such as pictures, documents, software installation packages, etc.
File sharing: Files can be stored on the server and shared with other users for download via URL.

3.2 Blob: front-end data export file excel, etc., data encryption

Return Blob scene:

Dynamic file download: Suitable for scenarios where file content needs to be generated dynamically, such as exporting data generated by the front end as files, such as exporting Excel, exporting PDF, etc.
Data encryption: Sensitive data can be encrypted and returned to the front end. The front end can save the encrypted data as a Blob object for download.

Reference: https://blog.csdn.net/qq_40298902/article/details/121779944

Guess you like

Origin blog.csdn.net/weixin_45565886/article/details/132796325