|
| 1 | +// Copyright 2025 CloudWeGo Authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +use std::os::unix::net::SocketAddr; |
| 16 | + |
| 17 | +use nix::unistd::unlink; |
| 18 | +use shmipc::{ |
| 19 | + Listener, compact::StreamExt, config::Config, stream::Stream, transport::DefaultUnixListen, |
| 20 | +}; |
| 21 | +use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 22 | + |
| 23 | +#[tokio::main] |
| 24 | +async fn main() { |
| 25 | + tracing_subscriber::fmt::init(); |
| 26 | + let dir = std::env::current_dir().unwrap(); |
| 27 | + let binding = dir.join("../ipc_test.sock"); |
| 28 | + let uds_path = binding.to_str().unwrap(); |
| 29 | + _ = unlink(uds_path); |
| 30 | + |
| 31 | + let mut ln = Listener::new( |
| 32 | + DefaultUnixListen, |
| 33 | + SocketAddr::from_pathname(binding).unwrap(), |
| 34 | + Config::default(), |
| 35 | + ) |
| 36 | + .await |
| 37 | + .unwrap(); |
| 38 | + |
| 39 | + loop { |
| 40 | + let stream = match ln.accept().await { |
| 41 | + Ok(stream) => stream, |
| 42 | + Err(e) => { |
| 43 | + eprintln!("failed to accept conn, err: {e}"); |
| 44 | + continue; |
| 45 | + } |
| 46 | + }; |
| 47 | + tokio::spawn(handle_stream(stream)); |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +async fn handle_stream(stream: Stream) { |
| 52 | + const EXPECTED_REQ: &str = "client say hello world!!!"; |
| 53 | + let mut buf = vec![0; 4096]; |
| 54 | + let mut conn = StreamExt::new(stream); |
| 55 | + |
| 56 | + loop { |
| 57 | + match conn.read_exact(&mut buf[..EXPECTED_REQ.len()]).await { |
| 58 | + Ok(len) => println!("read {len}"), |
| 59 | + Err(e) => { |
| 60 | + eprintln!("failed to read msg, err: {e}"); |
| 61 | + break; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + println!( |
| 66 | + "server receive request {}", |
| 67 | + str::from_utf8(&buf[..EXPECTED_REQ.len()]).unwrap() |
| 68 | + ); |
| 69 | + |
| 70 | + let resp_msg = "server hello world!!!"; |
| 71 | + conn.write_all(resp_msg.as_bytes()).await.unwrap(); |
| 72 | + conn.flush().await.unwrap(); |
| 73 | + } |
| 74 | + tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; |
| 75 | + conn.shutdown().await.unwrap(); |
| 76 | +} |
0 commit comments