How get &[u8] from Vec<u8>

How get &[u8] from Vec?

let encoded: Vec<u8> = bincode::rustc_serialize::encode(&st_player, bincode::SizeLimit::Infinite).unwrap();
let bytes : &[u8] = .....encoded.....; How?
socket.Send(bytes).unwrap();

Does &encoded[..] do what you want?

I want get array u8 from Vec. Then, send it. How to do it?

&[u8] is a slice of bytes, not an array.

Okey. How to send encoded through the socket? How to convert a encoded?

How to fix?

  let encoded: Vec<u8> = bincode::rustc_serialize::encode(&st_player, bincode::SizeLimit::Infinite).unwrap();
   let buffer = &encoded[..];
   socket.write(buffer).unwrap(); // Error. Why?

Sorry, but the Rust standard library doesn't provide crystal balls. Show us the full error and we can guess what's wrong.

3 Likes

Sorry.

Code:

extern crate bincode;
extern crate rustc_serialize;

use bincode::SizeLimit;
use bincode::rustc_serialize::{encode, decode};
use std::net::TcpListener;
use std::net::TcpStream;
#[derive(RustcEncodable, RustcDecodable, PartialEq)]
struct Player {
    m_name:String,
    m_id:i32,
}

fn game_start(mut player: TcpStream)
{
    println!("User connect.");
    let mut st_player = Player {m_name:"user".to_string(),m_id:12};
    let encoded: Vec<u8> = bincode::rustc_serialize::encode(&st_player, bincode::SizeLimit::Infinite).unwrap();
    let buffer = &encoded[..];
    player.write(buffer).unwrap();
}

fn main() {
    let listing = TcpListener::bind("127.0.0.1:5677").unwrap();
    for stream in listing.incoming() {
        match stream {
            Err(e) => { println!("Error:{}",e);}
            Ok(stream) => {
                      game_start(stream);
            }
        }
    }
    let mut text = String::new();
    std::io::stdin().read_line(&mut text);
}

In order for the write method to exist, the Write in std::io - Rust trait needs to be in scope. Try adding

use std::io::Write;

up with your use declarations.

1 Like

Thanks. As the error message tells you, you'll have to import std::io::Write into your module to be able to use the methods defined in the Write trait. Like this:

use std::io::Write;

Thank you very much!
I have another question.

bool Recv()
	{
		char recvbuf[DEFAULT_BUFFER_LENGTH];
		memset(&recvbuf, 0, sizeof(DEFAULT_BUFFER_LENGTH));
		int iResult = recv(ConnectSocket, recvbuf, 1000, 0);

		if (iResult > 0)
		{
			_Player* sa = new _Player();
			memset(sa, 0, sizeof(sa));
			strncpy((char*)sa, recvbuf, iResult);
			printf("PLAYER NAME: %s; PLAYER ID: %d", sa->m_num, sa->m_id );
			return true;
		}
                     return false;
	}

In the buffer has the value.

How to take structure?

Your C++ is bad: it relies on the internal representation of the objects, and does so across the network. Depending on what exactly you put in your “player” structure, it will break badly.

On the sending side, you must take each field of the structure that matters and convert it into an octet sequence depending on its type and its possible values; and then you must do the opposite on the receiving side. This is called serializing and deserializing. I strongly suggest you read some theoretical material about it.

C++ let you just cast the structure to a char array and access the internal structure, but Rust will not, unless you are using an unsafe block, and rightly so since it produces incorrect results.

4 Likes