1
0
mirror of https://github.com/actix/examples synced 2025-06-28 18:00:37 +02:00

upgrade example to actix-web 0.7

This commit is contained in:
Nikolay Kim
2018-07-16 12:36:53 +06:00
parent 0b52c7850e
commit 2cc1b23761
57 changed files with 913 additions and 693 deletions

View File

@ -5,8 +5,9 @@ extern crate bytes;
extern crate futures;
extern crate serde;
extern crate serde_json;
extern crate tokio_core;
extern crate tokio_codec;
extern crate tokio_io;
extern crate tokio_tcp;
#[macro_use]
extern crate serde_derive;
@ -15,10 +16,10 @@ use futures::Future;
use std::str::FromStr;
use std::time::Duration;
use std::{io, net, process, thread};
use tokio_core::net::TcpStream;
use tokio_io::codec::FramedRead;
use tokio_codec::FramedRead;
use tokio_io::io::WriteHalf;
use tokio_io::AsyncRead;
use tokio_tcp::TcpStream;
mod codec;
@ -27,10 +28,10 @@ fn main() {
// Connect to server
let addr = net::SocketAddr::from_str("127.0.0.1:12345").unwrap();
Arbiter::handle().spawn(
TcpStream::connect(&addr, Arbiter::handle())
Arbiter::spawn(
TcpStream::connect(&addr)
.and_then(|stream| {
let addr: Addr<Syn, _> = ChatClient::create(|ctx| {
let addr = ChatClient::create(|ctx| {
let (r, w) = stream.split();
ChatClient::add_stream(
FramedRead::new(r, codec::ClientChatCodec),
@ -87,7 +88,7 @@ impl Actor for ChatClient {
println!("Disconnected");
// Stop application on disconnect
Arbiter::system().do_send(actix::msgs::SystemExit(0));
System::current().stop();
}
}

View File

@ -6,8 +6,9 @@ extern crate futures;
extern crate rand;
extern crate serde;
extern crate serde_json;
extern crate tokio_core;
extern crate tokio_codec;
extern crate tokio_io;
extern crate tokio_tcp;
#[macro_use]
extern crate serde_derive;
@ -28,11 +29,11 @@ mod session;
/// This is our websocket route state, this state is shared with all route
/// instances via `HttpContext::state()`
struct WsChatSessionState {
addr: Addr<Syn, server::ChatServer>,
addr: Addr<server::ChatServer>,
}
/// Entry point for our route
fn chat_route(req: HttpRequest<WsChatSessionState>) -> Result<HttpResponse, Error> {
fn chat_route(req: &HttpRequest<WsChatSessionState>) -> Result<HttpResponse, Error> {
ws::start(
req,
WsChatSession {
@ -67,7 +68,7 @@ impl Actor for WsChatSession {
// before processing any other events.
// HttpContext::state() is instance of WsChatSessionState, state is shared
// across all routes within application
let addr: Addr<Syn, _> = ctx.address();
let addr = ctx.address();
ctx.state()
.addr
.send(server::Connect {
@ -187,7 +188,7 @@ fn main() {
let sys = actix::System::new("websocket-example");
// Start chat server actor in separate thread
let server: Addr<Syn, _> = Arbiter::start(|_| server::ChatServer::default());
let server = Arbiter::start(|_| server::ChatServer::default());
// Start tcp server in separate thread
let srv = server.clone();
@ -204,16 +205,16 @@ fn main() {
};
App::with_state(state)
// redirect to websocket.html
.resource("/", |r| r.method(http::Method::GET).f(|_| {
HttpResponse::Found()
.header("LOCATION", "/static/websocket.html")
.finish()
}))
// websocket
.resource("/ws/", |r| r.route().f(chat_route))
// static resources
.handler("/static/", fs::StaticFiles::new("static/"))
// redirect to websocket.html
.resource("/", |r| r.method(http::Method::GET).f(|_| {
HttpResponse::Found()
.header("LOCATION", "/static/websocket.html")
.finish()
}))
// websocket
.resource("/ws/", |r| r.route().f(chat_route))
// static resources
.handler("/static/", fs::StaticFiles::new("static/").unwrap())
}).bind("127.0.0.1:8080")
.unwrap()
.start();

View File

@ -15,7 +15,7 @@ use session;
#[derive(Message)]
#[rtype(usize)]
pub struct Connect {
pub addr: Recipient<Syn, session::Message>,
pub addr: Recipient<session::Message>,
}
/// Session is disconnected
@ -54,7 +54,7 @@ pub struct Join {
/// `ChatServer` manages chat rooms and responsible for coordinating chat
/// session. implementation is super primitive
pub struct ChatServer {
sessions: HashMap<usize, Recipient<Syn, session::Message>>,
sessions: HashMap<usize, Recipient<session::Message>>,
rooms: HashMap<String, HashSet<usize>>,
rng: RefCell<ThreadRng>,
}

View File

@ -4,10 +4,10 @@ use futures::Stream;
use std::str::FromStr;
use std::time::{Duration, Instant};
use std::{io, net};
use tokio_core::net::{TcpListener, TcpStream};
use tokio_io::codec::FramedRead;
use tokio_codec::FramedRead;
use tokio_io::io::WriteHalf;
use tokio_io::AsyncRead;
use tokio_tcp::{TcpListener, TcpStream};
use actix::prelude::*;
@ -23,7 +23,7 @@ pub struct ChatSession {
/// unique session id
id: usize,
/// this is address of chat server
addr: Addr<Syn, ChatServer>,
addr: Addr<ChatServer>,
/// Client must send ping at least once per 10 seconds, otherwise we drop
/// connection.
hb: Instant,
@ -45,7 +45,7 @@ impl Actor for ChatSession {
// register self in chat server. `AsyncContext::wait` register
// future within context, but context waits until this future resolves
// before processing any other events.
let addr: Addr<Syn, _> = ctx.address();
let addr = ctx.address();
self.addr
.send(server::Connect {
addr: addr.recipient(),
@ -133,7 +133,7 @@ impl Handler<Message> for ChatSession {
/// Helper methods
impl ChatSession {
pub fn new(
addr: Addr<Syn, ChatServer>,
addr: Addr<ChatServer>,
framed: actix::io::FramedWrite<WriteHalf<TcpStream>, ChatCodec>,
) -> ChatSession {
ChatSession {
@ -172,14 +172,14 @@ impl ChatSession {
/// Define tcp server that will accept incoming tcp connection and create
/// chat actors.
pub struct TcpServer {
chat: Addr<Syn, ChatServer>,
chat: Addr<ChatServer>,
}
impl TcpServer {
pub fn new(s: &str, chat: Addr<Syn, ChatServer>) {
pub fn new(s: &str, chat: Addr<ChatServer>) {
// Create server listener
let addr = net::SocketAddr::from_str("127.0.0.1:12345").unwrap();
let listener = TcpListener::bind(&addr, Arbiter::handle()).unwrap();
let listener = TcpListener::bind(&addr).unwrap();
// Our chat server `Server` is an actor, first we need to start it
// and then add stream on incoming tcp connections to it.
@ -187,12 +187,9 @@ impl TcpServer {
// items So to be able to handle this events `Server` actor has to
// implement stream handler `StreamHandler<(TcpStream,
// net::SocketAddr), io::Error>`
let _: () = TcpServer::create(|ctx| {
TcpServer::create(|ctx| {
ctx.add_message_stream(
listener
.incoming()
.map_err(|_| ())
.map(|(t, a)| TcpConnect(t, a)),
listener.incoming().map_err(|_| ()).map(|s| TcpConnect(s)),
);
TcpServer { chat: chat }
});
@ -206,7 +203,7 @@ impl Actor for TcpServer {
}
#[derive(Message)]
struct TcpConnect(TcpStream, net::SocketAddr);
struct TcpConnect(TcpStream);
/// Handle stream of TcpStream's
impl Handler<TcpConnect> for TcpServer {
@ -216,7 +213,7 @@ impl Handler<TcpConnect> for TcpServer {
// For each incoming connection we create `ChatSession` actor
// with out chat server address.
let server = self.chat.clone();
let _: () = ChatSession::create(|ctx| {
ChatSession::create(|ctx| {
let (r, w) = msg.0.split();
ChatSession::add_stream(FramedRead::new(r, ChatCodec), ctx);
ChatSession::new(server, actix::io::FramedWrite::new(w, ChatCodec, ctx))