Rust ネットワーク

TCPというプロトコルを使って情報を受け渡すサーバとクライアント

サーバ側

use std::net::{TcpListener,TcpStream};
use std::thread;
use std::io::{Read,Write,Error};

fn handle_data(mut stream: TcpStream) -> Result<(), Error> {
	println!("Connection from: {}", stream.peer_addr()?);
	let mut buf = [0; 512];
	loop {
		let byte_read = stream.read(&mut buf)?;
		for i in 0..byte_read {
			if buf[i] > 0x60 {
				buf[i] = buf[i] - 0x20;
			}
		}
		if byte_read == 0 {return Ok(());}
		stream.write(&buf[..byte_read])?;
	}
}

fn main() {
	let coninfo = "localhost:8000";
	let listener = TcpListener::bind(coninfo).expect("バインドできません。");
	for steam in listener.incoming(){
		match stream {
			Err(e) => {eprintln!("failed: {}", e)}
			Ok(stream) => {
				thread::spawn(move || {
					handle_data(stream).
						unwrap_or_else(|error| eprintln!("{:?}", error));
				});
			} 
		}
	}
}

クライアント側

use std::net::{TcpStream};
use std::str;
use std::io::{self,BufRead,BufReader,Write};

fn main() {
	let coinfo = "localhost:8000";

	let mut stream = TcpStream::connect(coinfo).expect("サーバに接続できません。");

	loop {
		let mut input = String::new();
		io::stdin().read_line(&mut input).expect("標準入力からの入力エラー");
		stream.write(input.as_bytes()).expect("サーバに送れません。");

		let mut reader = BufReader::new(&stream);
		reader.read_until(b'¥n', &mut buffer).expect("サーバから受け取れません");

		print!("{}", str::from_utf8(&buffer).expect("テキストを表示できません"));
	}
}

じゃんけんサーバ

use std::net::{TcpListener, TcpStream};
use std::thread;
use std::io::{Read,Write,Error};
use rand::{thread_rng, Rng};

fn handle_data(mut stream: TcpStream) -> Result<(), Error> {
	println!("Connection from: {}", stream.peer_addr()?);
	let mut buf = [0; 512];
	loop {
		let mut userte = false;
		let mut cpmsg = String::new();
		let mut msg = String::from("");
		let byte_read = stream.read(&mut buf)?;
		if byte_read == 0 {return Ok(());}

		let mut rng = thread_rng();
		let x: u16 = rng.gen_range(0, 3);

		match x {
			0 => cpmsg.insert_str(0, "私はグー"),
			1 => cpmsg.insert_str(0, "私はチョキ"),
			2 => cpmsg.insert_str(0, "私はパー"),
			_ => cpmsg.insert_str(0, ""),
		}
		let client_msg = String::from_utf8(buf.to_vec()).unwrap();
		msg.insert_str(0, &cpmsg);
		if client_msg.starts_with("グー") {
			userte=true;
			match x {
				0 => msg.push_str(":あいこ¥n");
				1 => msg.push_str(":あなたの勝ち¥n");
				2 => msg.push_str(":あなたの負け¥n");
				_ => ();
			}
		} else if client_msg.starts_with("チョキ"){
			userte=true;
			match x {
				0 => msg.push_str(":あなたの負け¥n");
				1 => msg.push_str(":あいこ¥n");
				2 => msg.push_str(":あなたの勝ち¥n");
				_ => ();
			}
		} else if client_msg.starts_with("パー"){
			userte=true;
			match x {
				0 => msg.push_str(":あなたの勝ち¥n");
				1 => msg.push_str(":あなたの負け¥n");
				2 => msg.push_str(":あいこ¥n");
				_ => ();
			}
		} if userte {
			let bytes = msg.as_bytes();
			let len = bytes.len();
			stream.write(&bytes[..len])?;
		} else {
			stream.write(&buf[..byte_read])?;
		}
		stream.flush()?;
	}
}

fn main() {
	let coninfo = "localhost:8000";
	let listener = TcpListener::bind(coninfo).expect("バインドできません。");
	for stream in listenr.incoming() {
		match stream {
			Err (e) => {eprintln!("failed: {}", e)}
			Ok(stream) => {
				thread::spawn(move || {
					handle_data(stream).
						unwrap_or_else(|error| eprintln!("{:?}", error));
				});
			}
		}
	}
}