Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add websocket support with Gun #9

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

ajuvercr
Copy link

Expand cowboy routing so /ws[...] are redirected to a Gun Websocket handler.
To facilitate this a ws macro is added to matcher that sets up 'route' by generating an ID.
This ID is a query parameter appended to the redirect URI and mapped to backend host, port and path.

Example:

dispatcher.ex

  match "/ws2" do
    ws(conn, "ws://localhost:7999")
  end

Route '/ws2/ to localhost:7999 with websockets.

Note: following redirects is not required in the websockets specs, and most browsers don't support this.

Example workarounds:

async function createRedirectedWebsocket(url) {
    // This prints an error to the console due to unexpected upgrade response
    const resp = await fetch(url);
    const ws_url = resp.url.replace(/^http/, 'ws');
    return new WebSocket(ws_url);
}

With the 'ws' npm package it is possible to set a followRedirects flag.

const WebSocket = require('ws')
const ws = new WebSocket('ws://localhost/ws2', options={'followRedirects': true});

@ajuvercr ajuvercr changed the title Add websocket support with Gun WIP: Add websocket support with Gun Jul 20, 2021
@ajuvercr ajuvercr changed the title WIP: Add websocket support with Gun Add websocket support with Gun Jul 21, 2021
Expand cowboy routing so /ws[...] are redirected to a Gun Websocket handler.
To facilitate this a ws macro is added to matcher that sets up 'route' by generating an ID.
This ID is a query parameter appended to the redirect URI and mapped to backend host, port and path.
@ajuvercr ajuvercr force-pushed the ws-dev branch 2 times, most recently from a14f85d to ad7b94d Compare July 21, 2021 18:31
@madnificent
Copy link
Member

Thanks for the PR!

Do WebSockets always need another port to operate on or can they be routed through? I'm missing that from the description here. If you'd update the README in the PR, I would consider this to be experimental functionality.

@ajuvercr
Copy link
Author

ajuvercr commented Sep 9, 2021

mu-dispatcher only uses one port, all requests to a URL starting like /ws/[...] are redirected to a Websocket handler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants