1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-25 00:12:59 +01:00
actix-extras/examples/websocket-chat/src/client.rs

148 lines
4.0 KiB
Rust
Raw Normal View History

2018-01-05 23:01:19 +01:00
#[macro_use] extern crate actix;
2017-10-21 02:16:17 +02:00
extern crate bytes;
extern crate byteorder;
extern crate futures;
extern crate tokio_io;
extern crate tokio_core;
extern crate serde;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
use std::{io, net, process, thread};
use std::str::FromStr;
use std::time::Duration;
use futures::Future;
use tokio_core::net::TcpStream;
use actix::prelude::*;
mod codec;
fn main() {
let sys = actix::System::new("chat-client");
// Connect to server
let addr = net::SocketAddr::from_str("127.0.0.1:12345").unwrap();
Arbiter::handle().spawn(
TcpStream::connect(&addr, Arbiter::handle())
.and_then(|stream| {
let addr: SyncAddress<_> = ChatClient.framed(stream, codec::ClientChatCodec);
// start console loop
thread::spawn(move|| {
loop {
let mut cmd = String::new();
if io::stdin().read_line(&mut cmd).is_err() {
println!("error");
return
}
addr.send(ClientCommand(cmd));
}
});
futures::future::ok(())
})
.map_err(|e| {
println!("Can not connect to server: {}", e);
process::exit(1)
})
);
println!("Running chat client");
sys.run();
}
struct ChatClient;
2018-01-05 23:01:19 +01:00
#[derive(Message)]
2017-10-21 02:16:17 +02:00
struct ClientCommand(String);
impl Actor for ChatClient {
type Context = FramedContext<Self>;
fn started(&mut self, ctx: &mut FramedContext<Self>) {
// start heartbeats otherwise server will disconnect after 10 seconds
self.hb(ctx)
}
2018-01-05 23:01:19 +01:00
fn stopping(&mut self, _: &mut FramedContext<Self>) {
println!("Disconnected");
// Stop application on disconnect
Arbiter::system().send(actix::msgs::SystemExit(0));
}
2017-10-21 02:16:17 +02:00
}
impl ChatClient {
fn hb(&self, ctx: &mut FramedContext<Self>) {
ctx.run_later(Duration::new(1, 0), |act, ctx| {
if ctx.send(codec::ChatRequest::Ping).is_ok() {
act.hb(ctx);
}
});
}
}
/// Handle stdin commands
2018-01-05 23:01:19 +01:00
impl Handler<ClientCommand> for ChatClient {
type Result = ();
fn handle(&mut self, msg: ClientCommand, ctx: &mut FramedContext<Self>) {
2017-10-21 02:16:17 +02:00
let m = msg.0.trim();
if m.is_empty() {
2018-01-05 23:01:19 +01:00
return
2017-10-21 02:16:17 +02:00
}
// we check for /sss type of messages
if m.starts_with('/') {
let v: Vec<&str> = m.splitn(2, ' ').collect();
match v[0] {
"/list" => {
let _ = ctx.send(codec::ChatRequest::List);
},
"/join" => {
if v.len() == 2 {
let _ = ctx.send(codec::ChatRequest::Join(v[1].to_owned()));
} else {
println!("!!! room name is required");
}
},
_ => println!("!!! unknown command"),
}
} else {
let _ = ctx.send(codec::ChatRequest::Message(m.to_owned()));
}
}
}
/// Server communication
impl FramedActor for ChatClient {
type Io = TcpStream;
type Codec = codec::ClientChatCodec;
2018-01-05 23:01:19 +01:00
fn handle(&mut self, msg: io::Result<codec::ChatResponse>, ctx: &mut FramedContext<Self>) {
2017-10-21 02:16:17 +02:00
match msg {
2018-01-05 23:01:19 +01:00
Err(_) => ctx.stop(),
Ok(msg) => match msg {
codec::ChatResponse::Message(ref msg) => {
println!("message: {}", msg);
}
codec::ChatResponse::Joined(ref msg) => {
println!("!!! joined: {}", msg);
2017-10-21 02:16:17 +02:00
}
2018-01-05 23:01:19 +01:00
codec::ChatResponse::Rooms(rooms) => {
println!("\n!!! Available rooms:");
for room in rooms {
println!("{}", room);
}
println!("");
}
_ => (),
2017-10-21 02:16:17 +02:00
}
}
}
}