Browse Source

refactored

open-trade 5 years ago
parent
commit
df9de95968
5 changed files with 31 additions and 50 deletions
  1. 9 9
      Cargo.lock
  2. 0 6
      Cargo.toml
  3. 1 1
      libs/hbb_common
  4. 2 1
      src/main.rs
  5. 19 33
      src/rendezvous_server.rs

+ 9 - 9
Cargo.lock

@@ -2,7 +2,7 @@
2
 # It is not intended for manual editing.
2
 # It is not intended for manual editing.
3
 [[package]]
3
 [[package]]
4
 name = "aho-corasick"
4
 name = "aho-corasick"
5
-version = "0.7.9"
5
+version = "0.7.10"
6
 source = "registry+https://github.com/rust-lang/crates.io-index"
6
 source = "registry+https://github.com/rust-lang/crates.io-index"
7
 dependencies = [
7
 dependencies = [
8
  "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
8
  "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -155,22 +155,22 @@ dependencies = [
155
 name = "hbb_common"
155
 name = "hbb_common"
156
 version = "0.1.0"
156
 version = "0.1.0"
157
 dependencies = [
157
 dependencies = [
158
+ "bytes 0.5.4 (registry+https://github.com/rust-lang/crates.io-index)",
159
+ "env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
160
+ "futures 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)",
161
+ "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
158
  "protobuf 2.10.2 (registry+https://github.com/rust-lang/crates.io-index)",
162
  "protobuf 2.10.2 (registry+https://github.com/rust-lang/crates.io-index)",
159
  "protobuf-codegen-pure 2.10.2 (registry+https://github.com/rust-lang/crates.io-index)",
163
  "protobuf-codegen-pure 2.10.2 (registry+https://github.com/rust-lang/crates.io-index)",
164
+ "tokio 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)",
165
+ "tokio-util 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
160
 ]
166
 ]
161
 
167
 
162
 [[package]]
168
 [[package]]
163
 name = "hbbs"
169
 name = "hbbs"
164
 version = "0.1.0"
170
 version = "0.1.0"
165
 dependencies = [
171
 dependencies = [
166
- "bytes 0.5.4 (registry+https://github.com/rust-lang/crates.io-index)",
167
- "env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
168
- "futures 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)",
169
  "hbb_common 0.1.0",
172
  "hbb_common 0.1.0",
170
- "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
171
  "simple-error 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
173
  "simple-error 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
172
- "tokio 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)",
173
- "tokio-util 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
174
 ]
174
 ]
175
 
175
 
176
 [[package]]
176
 [[package]]
@@ -385,7 +385,7 @@ name = "regex"
385
 version = "1.3.4"
385
 version = "1.3.4"
386
 source = "registry+https://github.com/rust-lang/crates.io-index"
386
 source = "registry+https://github.com/rust-lang/crates.io-index"
387
 dependencies = [
387
 dependencies = [
388
- "aho-corasick 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)",
388
+ "aho-corasick 0.7.10 (registry+https://github.com/rust-lang/crates.io-index)",
389
  "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
389
  "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
390
  "regex-syntax 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)",
390
  "regex-syntax 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)",
391
  "thread_local 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
391
  "thread_local 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -551,7 +551,7 @@ dependencies = [
551
 ]
551
 ]
552
 
552
 
553
 [metadata]
553
 [metadata]
554
-"checksum aho-corasick 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)" = "d5e63fd144e18ba274ae7095c0197a870a7b9468abc801dd62f190d80817d2ec"
554
+"checksum aho-corasick 0.7.10 (registry+https://github.com/rust-lang/crates.io-index)" = "8716408b8bc624ed7f65d223ddb9ac2d044c0547b6fa4b0d554f3a9540496ada"
555
 "checksum arc-swap 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "d7b8a9123b8027467bce0099fe556c628a53c8d83df0507084c31e9ba2e39aff"
555
 "checksum arc-swap 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "d7b8a9123b8027467bce0099fe556c628a53c8d83df0507084c31e9ba2e39aff"
556
 "checksum atty 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)" = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
556
 "checksum atty 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)" = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
557
 "checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
557
 "checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"

+ 0 - 6
Cargo.toml

@@ -7,12 +7,6 @@ edition = "2018"
7
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8
 
8
 
9
 [dependencies]
9
 [dependencies]
10
-tokio = { version = "0.2", features = ["full"] }
11
-tokio-util = { version = "0.3", features = ["full"] }
12
-log = "0.4"
13
-env_logger = "0.7"
14
-futures = "0.3"
15
-bytes = "0.5"
16
 simple-error = "0.2"
10
 simple-error = "0.2"
17
 hbb_common = { path = "libs/hbb_common" }
11
 hbb_common = { path = "libs/hbb_common" }
18
 
12
 

+ 1 - 1
libs/hbb_common

@@ -1 +1 @@
1
-Subproject commit 974815baaaa2efd886be73c3be8fb5931bcc29c4
1
+Subproject commit 7ba274fdaba5057fdefe6a3b47dc3255e78da3fe

+ 2 - 1
src/main.rs

@@ -1,10 +1,11 @@
1
 // https://tools.ietf.org/rfc/rfc5128.txt
1
 // https://tools.ietf.org/rfc/rfc5128.txt
2
 // https://blog.csdn.net/bytxl/article/details/44344855
2
 // https://blog.csdn.net/bytxl/article/details/44344855
3
 
3
 
4
+use hbb_common::{env_logger, log, tokio, ResultType};
4
 use hbbs::*;
5
 use hbbs::*;
5
 
6
 
6
 #[tokio::main]
7
 #[tokio::main]
7
-async fn main() -> Result<(), Box<dyn std::error::Error>> {
8
+async fn main() -> ResultType<()> {
8
     env_logger::init();
9
     env_logger::init();
9
     let addr = "0.0.0.0:21116";
10
     let addr = "0.0.0.0:21116";
10
     log::info!("Start Server {}", addr);
11
     log::info!("Start Server {}", addr);

+ 19 - 33
src/rendezvous_server.rs

@@ -1,13 +1,13 @@
1
-use bytes::{Bytes, BytesMut};
2
-use futures::SinkExt;
3
 use hbb_common::{
1
 use hbb_common::{
2
+    bytes::BytesMut,
3
+    log,
4
     message_proto::*,
4
     message_proto::*,
5
-    protobuf::{parse_from_bytes, Message as _},
6
-    AddrMangle,
5
+    protobuf::parse_from_bytes,
6
+    tokio::{net::UdpSocket, stream::StreamExt},
7
+    udp::FramedSocket,
8
+    AddrMangle, ResultType,
7
 };
9
 };
8
-use std::{collections::HashMap, error::Error, net::SocketAddr, time::Duration};
9
-use tokio::{net::UdpSocket, stream::StreamExt, time::delay_for};
10
-use tokio_util::{codec::BytesCodec, udp::UdpFramed};
10
+use std::{collections::HashMap, net::SocketAddr};
11
 
11
 
12
 pub struct Peer {
12
 pub struct Peer {
13
     socket_addr: SocketAddr,
13
     socket_addr: SocketAddr,
@@ -19,13 +19,10 @@ pub struct RendezvousServer {
19
     peer_map: PeerMap,
19
     peer_map: PeerMap,
20
 }
20
 }
21
 
21
 
22
-type FramedSocket = UdpFramed<BytesCodec>;
23
-type ResultType = Result<(), Box<dyn Error>>;
24
-
25
 impl RendezvousServer {
22
 impl RendezvousServer {
26
-    pub async fn start(addr: &str) -> ResultType {
23
+    pub async fn start(addr: &str) -> ResultType<()> {
27
         let socket = UdpSocket::bind(addr).await?;
24
         let socket = UdpSocket::bind(addr).await?;
28
-        let mut socket = UdpFramed::new(socket, BytesCodec::new());
25
+        let mut socket = FramedSocket::new(socket);
29
         let mut rs = Self {
26
         let mut rs = Self {
30
             peer_map: PeerMap::new(),
27
             peer_map: PeerMap::new(),
31
         };
28
         };
@@ -40,7 +37,7 @@ impl RendezvousServer {
40
         bytes: &BytesMut,
37
         bytes: &BytesMut,
41
         addr: SocketAddr,
38
         addr: SocketAddr,
42
         socket: &mut FramedSocket,
39
         socket: &mut FramedSocket,
43
-    ) -> ResultType {
40
+    ) -> ResultType<()> {
44
         if let Ok(msg_in) = parse_from_bytes::<Message>(&bytes) {
41
         if let Ok(msg_in) = parse_from_bytes::<Message>(&bytes) {
45
             match msg_in.union {
42
             match msg_in.union {
46
                 Some(Message_oneof_union::register_peer(rp)) => {
43
                 Some(Message_oneof_union::register_peer(rp)) => {
@@ -64,7 +61,7 @@ impl RendezvousServer {
64
                             socket_addr: AddrMangle::encode(&addr),
61
                             socket_addr: AddrMangle::encode(&addr),
65
                             ..Default::default()
62
                             ..Default::default()
66
                         });
63
                         });
67
-                        send_to(&msg_out, peer.socket_addr, socket).await?;
64
+                        socket.send(&msg_out, peer.socket_addr).await?;
68
                     }
65
                     }
69
                 }
66
                 }
70
                 Some(Message_oneof_union::punch_hole_sent(phs)) => {
67
                 Some(Message_oneof_union::punch_hole_sent(phs)) => {
@@ -76,7 +73,7 @@ impl RendezvousServer {
76
                         socket_addr: AddrMangle::encode(&addr),
73
                         socket_addr: AddrMangle::encode(&addr),
77
                         ..Default::default()
74
                         ..Default::default()
78
                     });
75
                     });
79
-                    send_to(&msg_out, addr_a, socket).await?;
76
+                    socket.send(&msg_out, addr_a).await?;
80
                 }
77
                 }
81
                 _ => {}
78
                 _ => {}
82
             }
79
             }
@@ -85,22 +82,11 @@ impl RendezvousServer {
85
     }
82
     }
86
 }
83
 }
87
 
84
 
88
-#[inline]
89
-pub async fn send_to(msg: &Message, addr: SocketAddr, socket: &mut FramedSocket) -> ResultType {
90
-    socket
91
-        .send((Bytes::from(msg.write_to_bytes().unwrap()), addr))
92
-        .await?;
93
-    Ok(())
94
-}
95
-
96
-#[inline]
97
-pub async fn sleep(sec: f32) {
98
-    delay_for(Duration::from_secs_f32(sec)).await;
99
-}
100
-
101
 #[cfg(test)]
85
 #[cfg(test)]
102
 mod tests {
86
 mod tests {
103
     use super::*;
87
     use super::*;
88
+    use hbb_common::tokio;
89
+    use std::time::Duration;
104
 
90
 
105
     #[allow(unused_must_use)]
91
     #[allow(unused_must_use)]
106
     #[tokio::main]
92
     #[tokio::main]
@@ -118,23 +104,23 @@ mod tests {
118
             // B register it to server
104
             // B register it to server
119
             let socket_b = UdpSocket::bind("127.0.0.1:0").await.unwrap();
105
             let socket_b = UdpSocket::bind("127.0.0.1:0").await.unwrap();
120
             let local_addr_b = socket_b.local_addr().unwrap();
106
             let local_addr_b = socket_b.local_addr().unwrap();
121
-            let mut socket_b = UdpFramed::new(socket_b, BytesCodec::new());
107
+            let mut socket_b = FramedSocket::new(socket_b);
122
             let mut msg_out = Message::new();
108
             let mut msg_out = Message::new();
123
             msg_out.set_register_peer(RegisterPeer {
109
             msg_out.set_register_peer(RegisterPeer {
124
                 hbb_addr: "123".to_string(),
110
                 hbb_addr: "123".to_string(),
125
                 ..Default::default()
111
                 ..Default::default()
126
             });
112
             });
127
-            send_to(&msg_out, addr_server, &mut socket_b).await;
113
+            socket_b.send(&msg_out, addr_server).await;
128
 
114
 
129
             // A send punch request to server
115
             // A send punch request to server
130
             let socket_a = UdpSocket::bind("127.0.0.1:0").await.unwrap();
116
             let socket_a = UdpSocket::bind("127.0.0.1:0").await.unwrap();
131
             let local_addr_a = socket_a.local_addr().unwrap();
117
             let local_addr_a = socket_a.local_addr().unwrap();
132
-            let mut socket_a = UdpFramed::new(socket_a, BytesCodec::new());
118
+            let mut socket_a = FramedSocket::new(socket_a);
133
             msg_out.set_punch_hole_request(PunchHoleRequest {
119
             msg_out.set_punch_hole_request(PunchHoleRequest {
134
                 hbb_addr: "123".to_string(),
120
                 hbb_addr: "123".to_string(),
135
                 ..Default::default()
121
                 ..Default::default()
136
             });
122
             });
137
-            send_to(&msg_out, addr_server, &mut socket_a).await;
123
+            socket_a.send(&msg_out, addr_server).await;
138
 
124
 
139
             println!(
125
             println!(
140
                 "A {:?} request punch hole to B {:?} via server {:?}",
126
                 "A {:?} request punch hole to B {:?} via server {:?}",
@@ -160,7 +146,7 @@ mod tests {
160
                     socket_addr: AddrMangle::encode(&remote_addr_a),
146
                     socket_addr: AddrMangle::encode(&remote_addr_a),
161
                     ..Default::default()
147
                     ..Default::default()
162
                 });
148
                 });
163
-                send_to(&msg_out, addr_server, &mut socket_b).await;
149
+                socket_b.send(&msg_out, addr_server).await;
164
             }
150
             }
165
 
151
 
166
             // on A side
152
             // on A side