doumou5109 2017-03-13 16:08
浏览 254

为什么在传输多个文件时WebSocket的实现要比HTTP / 2推送慢? (Node.js / Go)

I've been experiment with WebSockets and HTTP/2 libraries in Node and Go. My basic setup is to create a client and server, repeatedly send a file from the server and measure the time until each file is available at the client.

To my surprise, the HTTP/2 Push implementation performs significantly better than WebSocket (more than 5x faster in total time). Am I doing something wrong?

My Gorilla WebSocket and node-ws servers below:

Go

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())
  }
}

Node

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);
  }
});
  • 写回答

1条回答 默认 最新

  • doubingling4706 2017-03-19 20:38
    关注

    See https://github.com/gorilla/websocket/issues/228. The OP was measuring the time to open the streams with HTTP/2 Push, not the time to transfer all of the data over the streams. The OP found that Websockets are faster than HTTP/2 push.

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料