Updated, but client still doesn't display text
This commit is contained in:
parent
4291abbdaf
commit
ce45fb60ad
@ -1,6 +1,7 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "chat-reseau"
|
name = "chat-reseau"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
authors = ["Phuntsok Drak-pa <drakpa@drakpa.fr>"]
|
authors = ["Lucien Cartier-Tilet <drakpa@drakpa.fr>"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
bufstream = "0.1"
|
||||||
|
@ -1,6 +1,10 @@
|
|||||||
|
extern crate bufstream;
|
||||||
use std::net::TcpStream;
|
use std::net::TcpStream;
|
||||||
use std::io::{Read, Write};
|
use std::io::{stdin, stdout, Read, Write};
|
||||||
use std::io::{stdin, stdout};
|
// use std::sync::mpsc;
|
||||||
|
// use std::sync::mpsc::{Receiver, Sender};
|
||||||
|
use std::thread::spawn;
|
||||||
|
// use self::bufstream::BufStream;
|
||||||
|
|
||||||
fn get_entry() -> String {
|
fn get_entry() -> String {
|
||||||
let mut buf = String::new();
|
let mut buf = String::new();
|
||||||
@ -9,12 +13,51 @@ fn get_entry() -> String {
|
|||||||
buf.replace("\n", "").replace("\r", "")
|
buf.replace("\n", "").replace("\r", "")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn exchange_with_server(mut stream: TcpStream) {
|
fn read_from_server(
|
||||||
|
mut stream: TcpStream,
|
||||||
|
) {
|
||||||
|
let buff = &mut [0; 1024];
|
||||||
let stdout = stdout();
|
let stdout = stdout();
|
||||||
let mut io = stdout.lock();
|
let mut io = stdout.lock();
|
||||||
let buf = &mut [0; 1024];
|
loop {
|
||||||
|
match stream.read(buff) {
|
||||||
|
Ok(received) => {
|
||||||
|
if received < 1 {
|
||||||
|
// println!("Perte de connexion avec le serveur");
|
||||||
|
write!(io, "Perte de connexion avec le serveur\n").unwrap();
|
||||||
|
io.flush().unwrap();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
// println!("Perte de connexion avec le serveur");
|
||||||
|
write!(io, "Perte de connexion avec le serveur\n").unwrap();
|
||||||
|
io.flush().unwrap();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let reponse = String::from_utf8(buff.to_vec()).unwrap();
|
||||||
|
write!(io, "{}", reponse).unwrap();
|
||||||
|
io.flush().unwrap();
|
||||||
|
// println!("From server: {}", reponse);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exchange_with_server(
|
||||||
|
mut stream: TcpStream
|
||||||
|
) {
|
||||||
|
let stdout = stdout();
|
||||||
|
let mut io = stdout.lock();
|
||||||
|
let _buff = &mut [0; 1024];
|
||||||
|
|
||||||
|
let stream_cpy = stream.try_clone().unwrap();
|
||||||
|
spawn(move || {
|
||||||
|
// let stream_cpy = stream.try_clone().unwrap();
|
||||||
|
read_from_server(stream_cpy);
|
||||||
|
});
|
||||||
|
|
||||||
|
println!("Enter `quit` or `exit` when you want to leave");
|
||||||
|
|
||||||
println!("Enter `quit` when you want to leave");
|
|
||||||
loop {
|
loop {
|
||||||
write!(io, "> ").unwrap();
|
write!(io, "> ").unwrap();
|
||||||
io.flush().unwrap();
|
io.flush().unwrap();
|
||||||
@ -29,26 +72,53 @@ fn exchange_with_server(mut stream: TcpStream) {
|
|||||||
}
|
}
|
||||||
line => {
|
line => {
|
||||||
write!(stream, "{}\n", line).unwrap();
|
write!(stream, "{}\n", line).unwrap();
|
||||||
match stream.read(buf) {
|
// match stream.read(buff) {
|
||||||
Ok(received) => {
|
// Ok(received) => {
|
||||||
if received < 1 {
|
// if received < 1 {
|
||||||
println!("Perte de la connexion avec le serveur");
|
// println!("Perte de la connexion avec le serveur");
|
||||||
return;
|
// return;
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
Err(_) => {
|
// Err(_) => {
|
||||||
println!("Perte de la connexion avec le serveur");
|
// println!("Perte de la connexion avec le serveur");
|
||||||
return;
|
// return;
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
// println!("Réponse du serveur : {}", buf);
|
// println!("Réponse du serveur : {}", buf);
|
||||||
let reponse = String::from_utf8(buf.to_vec()).unwrap();
|
// let reponse = String::from_utf8(buf.to_vec()).unwrap();
|
||||||
println!("Réponse du serveur : {}", reponse);
|
// println!("Réponse du serveur : {}", reponse);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// fn exchange_with_server(stream: TcpStream) {
|
||||||
|
// let (chan, recv): (Sender<String>, Receiver<String>) = mpsc::channel();
|
||||||
|
// // let buf = &mut [0; 1024];
|
||||||
|
// spawn(move || {
|
||||||
|
// loop {
|
||||||
|
// let msg = recv.recv().unwrap();
|
||||||
|
// println!("{}", msg);
|
||||||
|
// }
|
||||||
|
// });
|
||||||
|
// println!("Enter `quit` or `exit` when you want to leave");
|
||||||
|
// loop {
|
||||||
|
// match &*get_entry() {
|
||||||
|
// "quit" => {
|
||||||
|
// println!("bye!");
|
||||||
|
// return;
|
||||||
|
// }
|
||||||
|
// "exit" => {
|
||||||
|
// println!("bye!");
|
||||||
|
// return;
|
||||||
|
// }
|
||||||
|
// line => {
|
||||||
|
// chan.send(format!("{}", line)).unwrap();
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
pub fn client(server_address: String) {
|
pub fn client(server_address: String) {
|
||||||
println!("Tentative de connexion a serveur...");
|
println!("Tentative de connexion a serveur...");
|
||||||
match TcpStream::connect(server_address) {
|
match TcpStream::connect(server_address) {
|
||||||
@ -58,6 +128,7 @@ pub fn client(server_address: String) {
|
|||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!("La connection au serveur a échoué : {}", e);
|
println!("La connection au serveur a échoué : {}", e);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,9 @@ fn main() {
|
|||||||
///////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////
|
||||||
println!("Opening server on port {}", args[1]);
|
println!("Opening server on port {}", args[1]);
|
||||||
// serveur(args[1].clone());
|
// serveur(args[1].clone());
|
||||||
server::serveur(args[1].clone());
|
let mut serv = String::from("127.0.0.1:");
|
||||||
|
serv.push_str(&args[1]);
|
||||||
|
server::serveur(serv);
|
||||||
} else if args.len() == 3 {
|
} else if args.len() == 3 {
|
||||||
///////////////////////////////////////////////////////////////////////
|
///////////////////////////////////////////////////////////////////////
|
||||||
// Client opened //
|
// Client opened //
|
||||||
|
@ -1,78 +1,92 @@
|
|||||||
use std::net::{TcpListener, TcpStream};
|
extern crate bufstream;
|
||||||
use std::io::{Read, Write};
|
use std::io::{BufRead, Write};
|
||||||
use std::thread;
|
use std::net::{SocketAddr, TcpListener, TcpStream};
|
||||||
|
use std::str::FromStr;
|
||||||
|
use std::sync::{mpsc, Arc, RwLock};
|
||||||
|
use std::sync::mpsc::{Receiver, Sender};
|
||||||
|
use std::thread::spawn;
|
||||||
|
use self::bufstream::BufStream;
|
||||||
|
|
||||||
fn handle_client(mut stream: &TcpStream, adresse: &str, name: String) {
|
fn handle_connection(
|
||||||
let mut msg: Vec<u8> = Vec::new();
|
stream: &mut BufStream<TcpStream>,
|
||||||
|
chan: Sender<String>,
|
||||||
|
arc: Arc<RwLock<Vec<String>>>,
|
||||||
|
) {
|
||||||
|
stream.write(b"Welcome this server!\n").unwrap();
|
||||||
|
stream
|
||||||
|
.write(b"Please input your username (max. 20chars): ")
|
||||||
|
.unwrap();
|
||||||
|
stream.flush().unwrap();
|
||||||
|
|
||||||
|
let mut name = String::new();
|
||||||
|
stream.read_line(&mut name).unwrap();
|
||||||
|
let name = name.trim_right();
|
||||||
|
stream
|
||||||
|
.write_fmt(format_args!("Hello, {}!\n", name))
|
||||||
|
.unwrap();
|
||||||
|
stream.flush().unwrap();
|
||||||
|
|
||||||
|
let mut pos = 0;
|
||||||
loop {
|
loop {
|
||||||
let buf = &mut [0; 10];
|
{
|
||||||
|
let lines = arc.read().unwrap();
|
||||||
|
for i in pos..lines.len() {
|
||||||
|
stream.write_fmt(format_args!("{}", lines[i])).unwrap();
|
||||||
|
pos = lines.len();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stream.write(b" > ").unwrap();
|
||||||
|
stream.flush().unwrap();
|
||||||
|
|
||||||
match stream.read(buf) {
|
let mut reads = String::new();
|
||||||
Ok(received) => {
|
stream.read_line(&mut reads).unwrap();
|
||||||
// si on a reçu 0 octet, ça veut dire que le client s'est déconnecté
|
if reads.trim().len() != 0 {
|
||||||
if received < 1 {
|
chan.send(format!("[{}] said: {}", name, reads)).unwrap();
|
||||||
println!("Client disconnected {}", adresse);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let mut x = 0;
|
|
||||||
|
|
||||||
for c in buf {
|
|
||||||
// si on a dépassé le nombre d'octets reçus, inutile de continuer
|
|
||||||
if x >= received {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
x += 1;
|
|
||||||
if *c == '\n' as u8 {
|
|
||||||
println!(
|
|
||||||
"message reçu {}({}) : {}",
|
|
||||||
name,
|
|
||||||
adresse,
|
|
||||||
// on convertit maintenant notre buffer en String
|
|
||||||
String::from_utf8(msg).unwrap()
|
|
||||||
);
|
|
||||||
|
|
||||||
stream.write(b"ok\n").unwrap();
|
|
||||||
|
|
||||||
msg = Vec::new();
|
|
||||||
} else {
|
|
||||||
msg.push(*c);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
println!("Client disconnected {}", adresse);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn serveur(port: String) {
|
pub fn serveur(addr: String) {
|
||||||
println!("Port: {}", port);
|
// Ouverture de la connexion sur socket
|
||||||
let mut serv = String::from("127.0.0.1:");
|
let addr = SocketAddr::from_str(&addr).unwrap();
|
||||||
serv.push_str(&port);
|
// Ajout d’un listener Tcp sur le socket
|
||||||
let listener = TcpListener::bind(serv.to_string()).unwrap();
|
let listener = TcpListener::bind(addr).unwrap();
|
||||||
|
|
||||||
println!("En attente d’un client...");
|
// création des receveurs et envoyeurs de strings asynchrones
|
||||||
|
let (sender, receiver): (Sender<String>, Receiver<String>) = mpsc::channel();
|
||||||
|
let arc: Arc<RwLock<Vec<String>>> = Arc::new(RwLock::new(Vec::new()));
|
||||||
|
let arc_w = arc.clone();
|
||||||
|
|
||||||
// Multi-client ///////////////////////////////////////////////////////////
|
// boucle infinie en parallèle pour recevoir des messages
|
||||||
|
spawn(move || {
|
||||||
|
loop {
|
||||||
|
// lit le message depuis le receveur
|
||||||
|
let msg = receiver.recv().unwrap();
|
||||||
|
print!("DEBUG: message {}", msg);
|
||||||
|
{
|
||||||
|
let mut arc_w = arc_w.write().unwrap();
|
||||||
|
arc_w.push(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Réception des clients
|
||||||
for stream in listener.incoming() {
|
for stream in listener.incoming() {
|
||||||
match stream {
|
match stream {
|
||||||
Ok(stream) => {
|
Err(e) => println!("Erreur écoute : {}", e),
|
||||||
let adresse = match stream.peer_addr() {
|
Ok(mut stream) => {
|
||||||
Ok(addr) => format!("[adresse : {}]", addr),
|
println!(
|
||||||
Err(_) => "inconnue".to_owned(),
|
"Nouvelle connexion de {} vers {}",
|
||||||
};
|
stream.peer_addr().unwrap(),
|
||||||
|
stream.local_addr().unwrap()
|
||||||
let name = String::from("Toto");
|
);
|
||||||
|
let sender = sender.clone();
|
||||||
println!("Nouveau client {}", adresse);
|
let arc = arc.clone();
|
||||||
thread::spawn(move || handle_client(&stream, &*adresse, name));
|
spawn(move || {
|
||||||
}
|
let mut stream = BufStream::new(stream);
|
||||||
Err(e) => {
|
handle_connection(&mut stream, sender, arc);
|
||||||
println!("La connexion du client a échoué : {}", e);
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
println!("En attente d’un autre client...");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user