This repository has been archived by the owner on Dec 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
chat.rs
74 lines (59 loc) · 1.93 KB
/
chat.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//! Simple chat server
extern crate actix;
extern crate actix_web;
extern crate sockjs;
extern crate env_logger;
use std::fs::File;
use std::io::Read;
use actix_web::*;
use actix::prelude::*;
use sockjs::{Message, Session, CloseReason, SockJSManager, SockJSContext};
struct Chat;
/// Sockjs session has to use `SockJSContext` context
impl Actor for Chat {
type Context = SockJSContext<Self>;
}
/// Session has to implement `Default` trait
impl Default for Chat {
fn default() -> Chat { Chat }
}
/// Sockjs session trait implementation
impl Session for Chat {
fn opened(&mut self, ctx: &mut SockJSContext<Self>) {
ctx.broadcast("Someone joined.")
}
fn closed(&mut self, ctx: &mut SockJSContext<Self>, _: CloseReason) {
ctx.broadcast("Someone left.")
}
}
/// Session has to be able to handle `sockjs::Message` messages
impl Handler<Message> for Chat {
type Result = ();
fn handle(&mut self, msg: Message, ctx: &mut SockJSContext<Self>) {
ctx.broadcast(msg);
}
}
fn main() {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
let sys = actix::System::new("sockjs-chat");
// Sockjs sessions manager
let sm: Addr<Syn, _> = SockJSManager::<Chat>::start_default();
server::new(
move || {
let s = sm.clone();
App::new()
.middleware(middleware::Logger::default())
.handler(
// Sockjs route handler
"/sockjs/", sockjs::SockJS::new(s.clone()))
.resource("/", |r| r.method(http::Method::GET).f(|_| -> Result<_> {
let mut file = File::open("examples/chat.html")?;
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(HttpResponse::Ok().body(content))
}))})
.bind("127.0.0.1:8080").unwrap()
.start();
let _ = sys.run();
}