-3

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);
  }
});
  • 2
    You're showing only a third of the relevant code (only the Websocket server, not the HTTP/2 push or the client side implementations) and asking about results you didn't paste (but you did summarize)... how are we expected to react to this? – Myst Mar 14 '17 at 00:44
  • On another note: HTTP/2 push has both the advantage of HTTP caching on the browser as well as the advantage that HTTP/2 is a persistent TCP/IP connection across all requests (no new connections are opened), while new Websocket connections are opened every time you refresh the page. I'm not sure what your requirements are, but the test might be a little biased towards HTTP/2 (these speeds aren't correct when it comes to first time clients / connections). – Myst Mar 14 '17 at 00:48

1 Answers1

1

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.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242