add domain socket

This commit is contained in:
anlicheng 2025-06-19 22:07:26 +08:00
parent 494d927137
commit fb18d7c356
2 changed files with 10 additions and 16 deletions

View File

@ -7,6 +7,5 @@ edition = "2021"
tokio = { version = "1.45.1", features = ["full"] }
tokio-modbus = "0.16.1"
tokio-serial = "5.4.1"
bytes = "1.0"
futures = "0.3.31"
tokio-util = "0.7.15"

View File

@ -1,9 +1,10 @@
use tokio::net::{UnixListener, UnixStream};
use tokio_util::codec::{Framed, LinesCodec};
//use tokio_util::codec::{Framed, LinesCodec};
use futures::SinkExt;
use tokio::io::AsyncReadExt;
//use tokio::io::AsyncReadExt;
const SOCKET_PATH: &str = "/tmp/rust_domain_socket.sock";
const SOCKET_PATH: &str = "/tmp/modbus.sock";
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 绑定Unix Domain Socket
@ -26,21 +27,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
async fn handle_client(mut stream: UnixStream) -> Result<(), Box<dyn std::error::Error>> {
let len = stream.read_u16().await.unwrap();
let mut buf = vec![0u8; len as usize];
// 使用行编解码器
let mut framed = Framed::new(stream, LinesCodec::new());
match stream.read_exact(&mut buf).await {
Ok(_) => {
// 发送欢迎消息
framed.send("Welcome to Rust Domain Socket Server").await?;
// 处理客户端消息
while let Some(message) = framed.next().await {
match message {
Ok(msg) => {
println!("Received: {}", msg);
framed.send(format!("Echo: {}", msg)).await?;
}
Err(e) => return Err(e.into()),
},
Err(err) => {
println!("read data get error: {}", err)
}
}