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

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

4

2 回答 2

4

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

于 2021-12-16T04:20:27.997 回答
2

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.

于 2021-12-16T04:07:25.927 回答