4
warp::serve(routes)
    .run(([127, 0, 0, 1], 3030))
    .await;

How can I listen to different ports for http requests and websocket connection?

kmdreko
  • 42,554
  • 6
  • 57
  • 106
AidonCason
  • 63
  • 5
  • See [Review: how to listen on both ipv4 and ipv6? · Issue #628 · seanmonstar/warp](https://github.com/seanmonstar/warp/issues/628) – Craig McQueen Jan 30 '23 at 01:03

2 Answers2

6

You can start two separate instances and run them concurrently:

tokio::join!(
    warp::serve(routes).run(([127, 0, 0, 1], 3030)),
    warp::serve(routes).run(([127, 0, 0, 1], 3031)),
);

Inspired by Run multiple actix app on different ports

kmdreko
  • 42,554
  • 6
  • 57
  • 106
5

Generally, there is no reason to use a separate port for WebSockets.

However, if you really want to listen on multiple ports (this has other use cases such as supporting plaintext and TLS off one Server instance), you can use Server::run_incoming. For this, you need to create your own listeners and combine their TcpListenerStreams using stream combinators.

use std::net::Ipv4Addr;
use tokio::net::TcpListener;
use tokio_stream::{StreamExt, wrappers::TcpListenerStream};

let listener1 = TcpListener::bind((Ipv4Addr::LOCALHOST, 3030)).await?;
let listener2 = TcpListener::bind((Ipv4Addr::LOCALHOST, 3031)).await?;

let stream1 = TcpListenerStream::new(listener1);
let stream2 = TcpListenerStream::new(listener2);

let combined = stream1.merge(stream2);

warp::serve(routes).run_incoming(combined).await?;

I admit that have not tried to compile this code myself, so there might be minor compiler errors, but the gist should be clear enough.

FallenWarrior
  • 656
  • 3
  • 16