Skip to content

Commit

Permalink
Make example work in Firefox
Browse files Browse the repository at this point in the history
  • Loading branch information
thomaseizinger committed Sep 11, 2023
1 parent 66e7844 commit 952160e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
4 changes: 1 addition & 3 deletions examples/browser-webrtc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,4 @@ wasm-pack build --target web --out-dir static
cargo run
```

3. Open the following in a Chromium-based[^1] browser: http://localhost:8080

[^1]: Support in other browsers has not been verified.
3. Open the URL printed in the terminal
22 changes: 16 additions & 6 deletions examples/browser-webrtc/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@ use libp2p::{
};
use libp2p_webrtc as webrtc;
use rand::thread_rng;
use std::{
net::Ipv6Addr,
net::{IpAddr, Ipv4Addr, SocketAddr},
};
use std::net::{Ipv4Addr, SocketAddr};
use tower_http::cors::{Any, CorsLayer};

#[tokio::main]
Expand All @@ -46,14 +43,22 @@ async fn main() -> anyhow::Result<()> {

let mut swarm = SwarmBuilder::with_tokio_executor(transport, behaviour, local_peer_id).build();

let address_webrtc = Multiaddr::from(Ipv6Addr::UNSPECIFIED)
let address_webrtc = Multiaddr::from(Ipv4Addr::UNSPECIFIED)
.with(Protocol::Udp(0))
.with(Protocol::WebRTCDirect);

swarm.listen_on(address_webrtc.clone())?;

let address = loop {
if let SwarmEvent::NewListenAddr { address, .. } = swarm.select_next_some().await {
if address
.iter()
.any(|e| e == Protocol::Ip4(Ipv4Addr::LOCALHOST))
{
log::debug!("Ignoring localhost address to make sure the example works in Firefox");
continue;
}

log::info!("Listening on: {address}");

break address;
Expand Down Expand Up @@ -91,6 +96,11 @@ struct StaticFiles;

/// Serve the Multiaddr we are listening on and the host files.
pub(crate) async fn serve(libp2p_transport: Multiaddr) {
let listen_addr = match libp2p_transport.iter().next() {
Some(Protocol::Ip4(addr)) => addr,
_ => panic!("Expected 1st protocol to be IP4"),
};

let server = Router::new()
.route("/", get(get_index))
.route("/index.html", get(get_index))
Expand All @@ -103,7 +113,7 @@ pub(crate) async fn serve(libp2p_transport: Multiaddr) {
.allow_methods([Method::GET]),
);

let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080);
let addr = SocketAddr::new(listen_addr.into(), 8080);

log::info!("Serving client files at http://{addr}");

Expand Down

0 comments on commit 952160e

Please sign in to comment.