Skip to content

Commit

Permalink
feat: traffic in websocket
Browse files Browse the repository at this point in the history
  • Loading branch information
XOR-op committed Mar 25, 2023
1 parent b8dbaf8 commit 196dc4f
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion boltconn/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ aho-corasick = "0.7.20"
anyhow = "1.0.66"
arrayref = "0.3.6"
async-trait = "0.1.58"
axum = "0.6.1"
axum = { version = "0.6.1", features = ["ws"] }
base64 = "0.21.0"
boltapi = { path = "../boltapi" }
boringtun = "0.5.2"
Expand Down
24 changes: 23 additions & 1 deletion boltconn/src/external/api_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ use crate::dispatch::{Dispatching, GeneralProxy};
use crate::network::configure::TunConfigure;
use crate::platform::process::ProcessInfo;
use crate::proxy::{AgentCenter, DumpedRequest, DumpedResponse, HttpCapturer, SessionManager};
use axum::extract::{Path, Query, State};
use axum::extract::ws::{Message, WebSocket};
use axum::extract::{ws::WebSocketUpgrade, Path, Query, State};
use axum::middleware::map_request;
use axum::response::IntoResponse;
use axum::routing::{delete, get, post};
use axum::{Json, Router};
use boltapi::{
Expand Down Expand Up @@ -61,6 +63,7 @@ impl ApiServer {
let wrapper = move |r| Self::auth(secret.clone(), r);
let app = Router::new()
.route("/logs", get(Self::get_logs))
.route("/ws/traffic", get(Self::ws_get_traffic))
.route(
"/tun",
get(Self::get_tun_configure).put(Self::set_tun_configure),
Expand Down Expand Up @@ -143,6 +146,25 @@ impl ApiServer {
}))
}

async fn ws_get_traffic(State(server): State<Self>, ws: WebSocketUpgrade) -> impl IntoResponse {
ws.on_upgrade(move |socket| Self::ws_get_traffic_inner(server, socket))
}

async fn ws_get_traffic_inner(server: Self, mut socket: WebSocket) {
loop {
// send traffic with 1 second interval
let data = json!(TrafficResp {
upload: server.stat_center.get_upload().load(Ordering::Relaxed),
download: server.stat_center.get_download().load(Ordering::Relaxed),
})
.to_string();
if socket.send(Message::Text(data)).await.is_err() {
return;
}
tokio::time::sleep(Duration::from_secs(1)).await;
}
}

async fn get_all_conn(State(server): State<Self>) -> Json<serde_json::Value> {
let list = server.stat_center.get_copy().await;
let mut result = Vec::new();
Expand Down

0 comments on commit 196dc4f

Please sign in to comment.