项目作者: faithandbrave

项目描述 :
Elixir/Phoenix chunked response example.
高级语言: Elixir
项目地址: git://github.com/faithandbrave/elixir-phoenix-chunked-response-example.git
创建时间: 2016-10-10T10:28:07Z
项目社区:https://github.com/faithandbrave/elixir-phoenix-chunked-response-example

开源协议:MIT License

下载


Elixir/Phoenix chunked response example

The repository is HTTP chunked transfer encoding example for Elixir/Phoenix. a.k.a HTTP stream response or EventSource.

chunk_demo.gif

How to Run

  1. mix deps.get
  2. npm install
  3. ./node_modules/brunch/bin/brunch b -p
  4. mix phoenix.server

Open http://localhost:4000, and push START button. Then, send start.sh results to client with HTTP chunked response.

How to send chunked response

1. Dependent libraries

  • mix.exs :
  1. def application do
  2. […,
  3. applications: […, :porcelain]]
  4. end
  5. defp deps do
  6. [
  7. …,
  8. {:porcelain, "~> 2.0"}
  9. ]
  10. end

Porcelain library is for execute shell-script.

  • package.json :
  1. "dependencies": {
  2. …,
  3. "stream-http": "~2.4.0"
  4. },

stream-http library is for client of chunked response.

2. Server code

  • web/controller/page_controller.ex
  1. def start(conn, _params) do
  2. # set-up chunked response
  3. conn = conn
  4. |> put_resp_content_type("text/event-stream")
  5. |> send_chunked(200)
  6. # send chunk data
  7. conn |> chunk("a")
  8. conn |> chunk("b")
  9. conn |> chunk("c")
  10. end

3. Client code

  • web/static/js/app.js
  1. import "stream-http"

Add client library.

  • web/templates/page/index.html
  1. var http = require('stream-http')
  2. var req = http.request(options, (res) => {
  3. res.setEncoding('utf8');
  4. res.on('data', (chunk) => {
  5. // Received chunked-response.
  6. // Add output text.
  7. document.getElementById('chunked-output').textContent = document.getElementById('chunked-output').textContent + chunk;
  8. });
  9. res.on('end', () => {
  10. // Received all data.
  11. });
  12. });
  13. req.write(postData);
  14. req.end();

Note

If you use Nginx, you should add proxy_buffering off;. Nginx cache server response, cause client receive all response at on time.

References