-3
我一直在使用Node和Go中的WebSockets和HTTP/2庫進行實驗。我的基本設置是創建客戶端和服務器,重複從服務器發送文件並測量時間,直到每個文件在客戶端可用。爲什麼在傳輸多個文件時WebSocket的實現比HTTP/2 Push慢呢? (Node.js/Go)
令我驚訝的是,HTTP/2 Push實現的性能明顯優於WebSocket(總時間快5倍以上)。難道我做錯了什麼?
我Gorilla WebSocket和node-ws服務器如下:
轉到
package main
import (
"net/http"
"io/ioutil"
"log"
"github.com/gorilla/websocket"
)
var file []byte
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func handler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal(err)
}
for i := 0; i < 100; i++ {
conn.WriteMessage(2, file)
}
}
func main() {
file, _ = ioutil.ReadFile("<path-to-file>")
http.HandleFunc("/", handler)
err := http.ListenAndServeTLS(":443", "<path-to-cert>", "<path-to-key>", nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}
節點
const WebSocket = require('ws');
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('<path-to-key>'),
cert: fs.readFileSync('<path-to-cert>')
};
var file = fs.readFileSync('<path-to-file>')
var httpServer = new https.createServer(options).listen(443);
var wss = new WebSocket.Server({
server: httpServer,
perMessageDeflate: false
});
wss.on('connection', function(ws) {
for (let i = 0; i < repetition; i++) {
ws.send(file);
}
});
您只顯示相關代碼的三分之一(只有Websocket服務器,而不是HTTP/2推送或客戶端實現),並詢問您沒有粘貼的結果(但您已經總結)...我們如何期待對此做出反應? – Myst
另一個說明:HTTP/2推送在瀏覽器中具有HTTP緩存的優點,以及HTTP/2是跨所有請求(不打開新連接)的持久TCP/IP連接的優點,而新Websocket連接每次刷新頁面時都會打開。我不確定你的要求是什麼,但測試可能會有點偏向於HTTP/2(當涉及到第一次客戶端/連接時,這些速度是不正確的)。 – Myst