Explorar o código

可以连上了,设置了header

skyfffire hai 3 semanas
pai
achega
95d7c6a35b
Modificáronse 2 ficheiros con 33 adicións e 4 borrados
  1. 0 1
      .idea/vcs.xml
  2. 33 3
      src/exchange/socket_tool.rs

+ 0 - 1
.idea/vcs.xml

@@ -2,6 +2,5 @@
 <project version="4">
   <component name="VcsDirectoryMappings">
     <mapping directory="" vcs="Git" />
-    <mapping directory="$PROJECT_DIR$/rust-crypto-lib-base" vcs="Git" />
   </component>
 </project>

+ 33 - 3
src/exchange/socket_tool.rs

@@ -10,7 +10,9 @@ use tokio::net::TcpStream;
 use tokio::sync::Mutex;
 use tokio::time::Instant;
 use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
-use tokio_tungstenite::tungstenite::{Error, Message};
+use tokio_tungstenite::tungstenite::{http, Error, Message};
+use tokio_tungstenite::tungstenite::handshake::client::Request;
+use tokio_tungstenite::tungstenite::handshake::client::generate_key;
 use tracing::{error, info, trace, warn};
 
 use crate::exchange::proxy;
@@ -182,7 +184,35 @@ impl AbstractWsMode {
               F: Fn(Response) -> Future + Clone,
               Future: future::Future<Output=()> + Send + 'static,
     {
-        // 1.是否走代理
+        // 提取host
+        let parsed_uri: http::Uri = address_url.parse().unwrap();
+        let host_domain = parsed_uri.host().ok_or("URI 缺少主机名").unwrap().to_string();
+        let host_header_value = if let Some(port) = parsed_uri.port_u16() {
+            // 如果端口不是默认的 80 (for ws) 或 443 (for wss),则需要包含端口
+            // 这里只是简单地判断,更严谨的判断可以根据 scheme 来
+            match parsed_uri.scheme_str() {
+                Some("ws") if port == 80 => host_domain.to_string(),
+                Some("wss") if port == 443 => host_domain.to_string(),
+                _ => format!("{}:{}", host_domain, port), // 否则包含端口
+            }
+        } else {
+            host_domain.to_string() // 没有端口或使用默认端口
+        };
+
+        // 通过构建request的方式进行ws链接,可以携带header
+        let request = Request::builder()
+            .method("GET")
+            .uri(&address_url)
+            .header("Sec-WebSocket-Key", generate_key())
+            .header("Sec-WebSocket-Version", "13")
+            .header("Host", host_header_value)
+            .header("User-Agent", "RustClient/1.0")
+            .header("Upgrade", "websocket")
+            .header("Connection", "Upgrade")
+            .body(())
+            .unwrap();
+
+        // 判断是否通过代理访问
         let proxy = match proxy::ParsingDetail::env_proxy(ProxyEnum::WS) {
             ProxyResponseEnum::NO => {
                 // trace!("非 代理");
@@ -194,7 +224,7 @@ impl AbstractWsMode {
             }
         };
 
-        match connect_async(address_url.clone(), proxy).await {
+        match connect_async(request, proxy).await {
             Ok((ws_stream, _)) => {
                 trace!("socket 链接成功,{}。", address_url);