mirror of
https://github.com/actix/examples
synced 2024-11-23 22:41:07 +01:00
migrate websocket-chat example
This commit is contained in:
parent
5ffbaacdce
commit
e166c66f0b
@ -37,10 +37,7 @@ members = [
|
|||||||
"unix-socket",
|
"unix-socket",
|
||||||
# "web-cors/backend",
|
# "web-cors/backend",
|
||||||
# "websocket",
|
# "websocket",
|
||||||
# "websocket-chat",
|
"websocket-chat",
|
||||||
# "websocket-chat-broker",
|
# "websocket-chat-broker",
|
||||||
# "websocket-tcp-chat",
|
# "websocket-tcp-chat",
|
||||||
]
|
]
|
||||||
|
|
||||||
[patch.crates-io]
|
|
||||||
actix-http = { git = "https://github.com/actix/actix-web.git" }
|
|
||||||
|
@ -60,7 +60,10 @@ async fn add(
|
|||||||
|
|
||||||
/// This handler manually parse json object. Bytes object supports FromRequest trait (extractor)
|
/// This handler manually parse json object. Bytes object supports FromRequest trait (extractor)
|
||||||
/// and could be loaded from request payload automatically
|
/// and could be loaded from request payload automatically
|
||||||
async fn index_add(body: web::Bytes, pool: web::Data<Pool>) -> Result<HttpResponse, Error> {
|
async fn index_add(
|
||||||
|
body: web::Bytes,
|
||||||
|
pool: web::Data<Pool>,
|
||||||
|
) -> Result<HttpResponse, Error> {
|
||||||
// body is loaded, now we can deserialize id with serde-json
|
// body is loaded, now we can deserialize id with serde-json
|
||||||
let r_obj = serde_json::from_slice::<MyUser>(&body);
|
let r_obj = serde_json::from_slice::<MyUser>(&body);
|
||||||
|
|
||||||
|
@ -1,8 +1,7 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "websocket-example"
|
name = "websocket-example"
|
||||||
version = "0.1.0"
|
version = "2.0.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
workspace = ".."
|
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
@ -10,16 +9,16 @@ name = "websocket-chat-server"
|
|||||||
path = "src/main.rs"
|
path = "src/main.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix = "0.8.2"
|
actix-rt = "1.0.0"
|
||||||
actix-web = "1.0.0"
|
actix = "0.9.0-alpha.1"
|
||||||
actix-web-actors = "1.0.0"
|
actix-web = "2.0.0-alpha.5"
|
||||||
actix-files = "0.1.1"
|
actix-web-actors = "2.0.0-alpha.1"
|
||||||
|
actix-files = "0.2.0-alpha.3"
|
||||||
|
|
||||||
rand = "0.6"
|
rand = "0.6"
|
||||||
bytes = "0.4"
|
bytes = "0.5.3"
|
||||||
byteorder = "1.1"
|
byteorder = "1.1"
|
||||||
futures = "0.1.25"
|
futures = "0.3.1"
|
||||||
tokio-io = "0.1"
|
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
|
@ -13,7 +13,7 @@ const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
|
|||||||
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
|
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||||
|
|
||||||
/// Entry point for our route
|
/// Entry point for our route
|
||||||
fn chat_route(
|
async fn chat_route(
|
||||||
req: HttpRequest,
|
req: HttpRequest,
|
||||||
stream: web::Payload,
|
stream: web::Payload,
|
||||||
srv: web::Data<Addr<server::ChatServer>>,
|
srv: web::Data<Addr<server::ChatServer>>,
|
||||||
@ -71,7 +71,7 @@ impl Actor for WsChatSession {
|
|||||||
// something is wrong with chat server
|
// something is wrong with chat server
|
||||||
_ => ctx.stop(),
|
_ => ctx.stop(),
|
||||||
}
|
}
|
||||||
fut::ok(())
|
fut::ready(())
|
||||||
})
|
})
|
||||||
.wait(ctx);
|
.wait(ctx);
|
||||||
}
|
}
|
||||||
@ -93,8 +93,20 @@ impl Handler<server::Message> for WsChatSession {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// WebSocket message handler
|
/// WebSocket message handler
|
||||||
impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
|
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsChatSession {
|
||||||
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
|
fn handle(
|
||||||
|
&mut self,
|
||||||
|
msg: Result<ws::Message, ws::ProtocolError>,
|
||||||
|
ctx: &mut Self::Context,
|
||||||
|
) {
|
||||||
|
let msg = match msg {
|
||||||
|
Err(_) => {
|
||||||
|
ctx.stop();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Ok(msg) => msg,
|
||||||
|
};
|
||||||
|
|
||||||
println!("WEBSOCKET MESSAGE: {:?}", msg);
|
println!("WEBSOCKET MESSAGE: {:?}", msg);
|
||||||
match msg {
|
match msg {
|
||||||
ws::Message::Ping(msg) => {
|
ws::Message::Ping(msg) => {
|
||||||
@ -126,7 +138,7 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
|
|||||||
}
|
}
|
||||||
_ => println!("Something is wrong"),
|
_ => println!("Something is wrong"),
|
||||||
}
|
}
|
||||||
fut::ok(())
|
fut::ready(())
|
||||||
})
|
})
|
||||||
.wait(ctx)
|
.wait(ctx)
|
||||||
// .wait(ctx) pauses all events in context,
|
// .wait(ctx) pauses all events in context,
|
||||||
@ -173,6 +185,9 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
|
|||||||
ws::Message::Close(_) => {
|
ws::Message::Close(_) => {
|
||||||
ctx.stop();
|
ctx.stop();
|
||||||
}
|
}
|
||||||
|
ws::Message::Continuation(_) => {
|
||||||
|
ctx.stop();
|
||||||
|
}
|
||||||
ws::Message::Nop => (),
|
ws::Message::Nop => (),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -199,14 +214,14 @@ impl WsChatSession {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx.ping("");
|
ctx.ping(b"");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> std::io::Result<()> {
|
#[actix_rt::main]
|
||||||
|
async fn main() -> std::io::Result<()> {
|
||||||
env_logger::init();
|
env_logger::init();
|
||||||
let sys = System::new("ws-example");
|
|
||||||
|
|
||||||
// Start chat server actor
|
// Start chat server actor
|
||||||
let server = server::ChatServer::default().start();
|
let server = server::ChatServer::default().start();
|
||||||
@ -227,7 +242,6 @@ fn main() -> std::io::Result<()> {
|
|||||||
.service(fs::Files::new("/static/", "static/"))
|
.service(fs::Files::new("/static/", "static/"))
|
||||||
})
|
})
|
||||||
.bind("127.0.0.1:8080")?
|
.bind("127.0.0.1:8080")?
|
||||||
.start();
|
.start()
|
||||||
|
.await
|
||||||
sys.run()
|
|
||||||
}
|
}
|
||||||
|
@ -8,6 +8,7 @@ use std::collections::{HashMap, HashSet};
|
|||||||
|
|
||||||
/// Chat server sends this messages to session
|
/// Chat server sends this messages to session
|
||||||
#[derive(Message)]
|
#[derive(Message)]
|
||||||
|
#[rtype(result = "()")]
|
||||||
pub struct Message(pub String);
|
pub struct Message(pub String);
|
||||||
|
|
||||||
/// Message for chat server communications
|
/// Message for chat server communications
|
||||||
@ -21,12 +22,14 @@ pub struct Connect {
|
|||||||
|
|
||||||
/// Session is disconnected
|
/// Session is disconnected
|
||||||
#[derive(Message)]
|
#[derive(Message)]
|
||||||
|
#[rtype(result = "()")]
|
||||||
pub struct Disconnect {
|
pub struct Disconnect {
|
||||||
pub id: usize,
|
pub id: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send message to specific room
|
/// Send message to specific room
|
||||||
#[derive(Message)]
|
#[derive(Message)]
|
||||||
|
#[rtype(result = "()")]
|
||||||
pub struct ClientMessage {
|
pub struct ClientMessage {
|
||||||
/// Id of the client session
|
/// Id of the client session
|
||||||
pub id: usize,
|
pub id: usize,
|
||||||
@ -45,6 +48,7 @@ impl actix::Message for ListRooms {
|
|||||||
|
|
||||||
/// Join room, if room does not exists create new one.
|
/// Join room, if room does not exists create new one.
|
||||||
#[derive(Message)]
|
#[derive(Message)]
|
||||||
|
#[rtype(result = "()")]
|
||||||
pub struct Join {
|
pub struct Join {
|
||||||
/// Client id
|
/// Client id
|
||||||
pub id: usize,
|
pub id: usize,
|
||||||
|
Loading…
Reference in New Issue
Block a user