Unix sockets read

⚓ Rust    📅 2025-11-13    👤 surdeus    👁️ 4      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Unix sockets read

Hi folks,

I try to make a Unix socket demo using rust and netcat (nc).
nc to nc works fine, I run on the same Unix (Arch linux) machine two terminals:
Server:
nc -U /tmp/demo.sock -l
Client:
nc -U /tmp/demo.sock

and what I type on one terminal, I see it on the other (and vice versa).

Now I want to replace the server nc with a rust program.

use std::io::prelude::*;
use std::os::unix::net::{UnixListener, UnixStream};
use std::thread;
use std::time::Duration;

fn main() -> std::io::Result<()> {
    let sock_path = "/tmp/demo1.sock";
    let _ = std::fs::remove_file(sock_path);
    let listener = UnixListener::bind(sock_path)?;
    for stream in listener.incoming() {
        match stream {
            Ok(mut stream) => {
                stream.write_all(b"hello world\n")?;
                thread::spawn(|| handle_client(stream));
            }
            Err(e) => {
                println!("listener.incoming() err: {}", e);
                break;
            }
        }
    }
    Ok(())
}

fn handle_client(mut stream: UnixStream) {
    println!("handle_client");
    let sw1 = false;
    if sw1 {
        let mut buf_str = String::with_capacity(50);
        // stream.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
        match stream.read_to_string(&mut buf_str) {
            Ok(v) => {
                println!("read {} bytes: {}", v, buf_str);
            }
            Err(e) => {
                println!("read_to_string failed: {}", e);
            }
        }
    } else {
        let mut buf_bytes: Vec<u8> = vec![0; 50];
        loop {
            match stream.read(&mut buf_bytes) {
                Ok(v) => {
                    println!("read {} bytes: {:?}", v, buf_bytes);
                }
                Err(e) => {
                    println!("read_to_string failed: {}", e);
                }
            }
        }
    }
}

When sw1 == false I can send from nc data to the server, it works as expected.
Q1: When sw1 == true, I start this program and then on a separate terminal run client nc. 'hello' appears, but when I type something, I don't see it on the rust server. Why EOF from netcat isn't detected (i. e. read_to_string() blocks)? On the nc side, enter doesn't work (as it does when I test nc - nc), ^d neither, only when I type something and exit nc (^c) I see that text on the server side.
Q2: Any better idea than rm socket file -> bind? Could it be problematic?

Many thanks!

4 posts - 2 participants

Read full topic

🏷️ Rust_feed