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 //! cargo build --example ylong_io_tcp_client --no-default-features
15 //! --features="ylong_tcp" Uses with ylong_io_tcp_server, start
16 //! ylong_io_tcp_server first, then start ylong_io_tcp_client
17 
18 use std::io::{Read, Write};
19 use std::thread::sleep;
20 use std::time::Duration;
21 
22 use ylong_io::TcpStream;
23 
main()24 fn main() {
25     let addr = "127.0.0.1:1234".parse().unwrap();
26     let mut buffer = [0_u8; 1024];
27     let mut stream = match TcpStream::connect(addr) {
28         Err(err) => {
29             println!("TcpStream::connect err {err}");
30             return;
31         }
32         Ok(addr) => addr,
33     };
34     loop {
35         sleep(Duration::from_micros(300));
36         match stream.read(&mut buffer) {
37             Ok(_) => {
38                 println!("1.Receive msg: {}\n", String::from_utf8_lossy(&buffer));
39                 break;
40             }
41             Err(_) => continue,
42         }
43     }
44 
45     println!("client socket: {stream:?}");
46 
47     match stream.write(b"Hello World") {
48         Ok(n) => println!("send len: {n}"),
49         _ => println!("send failed"),
50     }
51 
52     if stream.read(&mut buffer).is_ok() {
53         println!("2.Receive msg: {}\n", String::from_utf8_lossy(&buffer));
54     }
55 }
56