socketsrustdatagram

Rust Datagram Socket: How to receive string from bytes


I am creating simple client server communication with unix datagram socket in Rust. I am receiving message to server from client with bytes length but not able to converting back to the original string I sent from client. I have tried https://doc.rust-lang.org/std/str/fn.from_utf8.html and from_utf8_lossy but had no success. Here is the code.

How to get original string on the server?

Server side:

use std::os::unix::net::UnixDatagram;
use std::path::Path;

fn unlink_socket (path: impl AsRef<Path>) {
    let path = path.as_ref();
    if Path::new(path).exists() {
        let result = std::fs::remove_file(path);
        match result {
            Err(e) => {
                println!("Couldn't remove the file: {:?}", e);
            },
            _ => {}
        }
    }
}

pub fn tcp_datagram_server() {
    pub static FILE_PATH: &'static str = "/tmp/datagram.sock";
    let mut buf = vec![0; 1024];
    unlink_socket(FILE_PATH);
    let socket = match UnixDatagram::bind(FILE_PATH) {
        Ok(socket) => socket,
        Err(e) => {
            println!("Couldn't bind: {:?}", e);
            return;
        }
    };
    println!("Waiting for client to connect...");
    loop {
        let received_bytes = socket.recv(buf.as_mut_slice()).expect("recv function failed");
        println!("Received {:?}", received_bytes);
    }
}

fn main() {
   tcp_datagram_server();
}

client side:

use std::sync::mpsc;
use std::os::unix::net::UnixDatagram;
use std::path::Path;
use std::io::prelude::*;

pub fn tcp_datagram_client() {
    pub static FILE_PATH: &'static str = "/tmp/datagram.sock";
    let socket = UnixDatagram::unbound().unwrap();
    match socket.connect(FILE_PATH) {
        Ok(socket) => socket,
        Err(e) => {
            println!("Couldn't connect: {:?}", e);
            return;
        }
    };
    println!("TCP client Connected to TCP Server {:?}", socket);
    loop {
        socket.send(b"Hello from client to server").expect("recv function failed");
    }
}

fn main() {
   tcp_datagram_client();
}

Result I am getting on the server side:

Waiting for client to connect...
Received 27
Received 27
Received 27
Received 27
Received 27
Received 27
Received 27


Solution

  • std::str::from_utf8(buf.as_slice()).unwrap() should give you a &str of the data, which you can convert to a String if need be:

    socket.recv(buf.as_mut_slice()).expect("recv function failed");
    let message = std::str::from_utf8(buf.as_slice()).expect("utf-8 convert failed");
    

    The first line reads the data into buf and the second line converts the data in buf into a str.