• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 //! An example for `tcp`
15 use std::net::SocketAddr;
16 
17 use ylong_runtime::io::{AsyncReadExt, AsyncWriteExt};
18 use ylong_runtime::net::{TcpListener, TcpStream};
19 
20 const BUF_SIZE: usize = 10000;
21 const LOOP_NUM: usize = 1000;
22 const TASK_NUM: usize = 120;
23 
ylong_tcp_server(addr: SocketAddr)24 async fn ylong_tcp_server(addr: SocketAddr) {
25     let tcp = TcpListener::bind(addr).await.unwrap();
26     let (mut stream, _) = tcp.accept().await.unwrap();
27     for _ in 0..LOOP_NUM {
28         let mut buf = [0; BUF_SIZE];
29         stream.read_exact(&mut buf).await.unwrap();
30         assert_eq!(buf, [3; BUF_SIZE]);
31 
32         let buf = [2; BUF_SIZE];
33         stream.write_all(&buf).await.unwrap();
34     }
35 }
36 
ylong_tcp_client(addr: SocketAddr)37 async fn ylong_tcp_client(addr: SocketAddr) {
38     let mut tcp = TcpStream::connect(addr).await;
39     while tcp.is_err() {
40         tcp = TcpStream::connect(addr).await;
41     }
42     let mut tcp = tcp.unwrap();
43     for _ in 0..LOOP_NUM {
44         let buf = [3; BUF_SIZE];
45         tcp.write_all(&buf).await.unwrap();
46 
47         let mut buf = [0; BUF_SIZE];
48         tcp.read_exact(&mut buf).await.unwrap();
49         assert_eq!(buf, [2; BUF_SIZE]);
50     }
51 }
52 
ylong_tcp_send_recv()53 fn ylong_tcp_send_recv() {
54     let basic_addr = "127.0.0.1:";
55     let port = 8181;
56     let mut handlers = Vec::new();
57     for i in 0..TASK_NUM {
58         let addr = (basic_addr.to_owned() + &*(port + i).to_string())
59             .parse()
60             .unwrap();
61         handlers.push(ylong_runtime::spawn(ylong_tcp_server(addr)));
62         handlers.push(ylong_runtime::spawn(ylong_tcp_client(addr)));
63     }
64     for handler in handlers {
65         ylong_runtime::block_on(handler).unwrap();
66     }
67 }
68 
main()69 fn main() {
70     ylong_tcp_send_recv();
71 }
72