1
0
mirror of https://github.com/actix/examples synced 2025-06-26 17:17:42 +02:00

Restructure folders (#411)

This commit is contained in:
Daniel T. Rodrigues
2021-02-25 21:57:58 -03:00
committed by GitHub
parent 9db98162b2
commit c3407627d0
334 changed files with 127 additions and 120 deletions

View File

@ -0,0 +1,24 @@
[package]
name = "websocket-chat-broker"
version = "0.1.1"
authors = [
"Chris Ricketts <chris.ricketts@steribar.com>",
"Rob Ede <robjtede@icloud.com>",
]
edition = "2018"
[[bin]]
name = "server"
path = "src/main.rs"
[dependencies]
actix = "0.10"
actix-broker = "0.3.1"
actix-files = "0.4"
actix-rt = "1"
actix-web = "3"
actix-web-actors = "3"
env_logger = "0.8"
futures = "0.3"
log = "0.4"
rand = "0.7"

View File

@ -0,0 +1,29 @@
# Websocket chat broker example
This is a different implementation of the
[websocket chat example](https://github.com/actix/examples/tree/master/websocket-chat)
Differences:
* Chat Server Actor is a System Service that runs in the same thread as the HttpServer/WS Listener.
* The [actix-broker](https://github.com/Chris-Ricketts/actix-broker) crate is used to facilitate the sending of some messages between the Chat Session and Server Actors where the session does not require a response.
* The Client is not required to send Ping messages. The Chat Server Actor auto-clears dead sessions.
Possible Improvements:
* Could the Chat Server Actor be simultaneously a System Service (accessible to the Chat Session via the System Registry) and also run in a seperate thread?
## Server
Chat server listens for incoming tcp connections. Server can access several types of message:
* `/list` - list all available rooms
* `/join name` - join room, if room does not exist, create new one
* `/name name` - set session name
* `some message` - just string, send message to all peers in same room
To start server use command: `cargo run`
## WebSocket Browser Client
Open url: [http://localhost:8080/](http://localhost:8080/)

View File

@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""websocket cmd client for actix/websocket-tcp-chat example."""
import argparse
import asyncio
import signal
import sys
import aiohttp
queue = asyncio.Queue()
async def start_client(url, loop):
name = input('Please enter your name: ')
ws = await aiohttp.ClientSession().ws_connect(url, autoclose=False, autoping=False)
def stdin_callback():
line = sys.stdin.buffer.readline().decode('utf-8')
if not line:
loop.stop()
else:
# Queue.put is a coroutine, so you can't call it directly.
asyncio.ensure_future(queue.put(ws.send_str(name + ': ' + line)))
loop.add_reader(sys.stdin, stdin_callback)
async def dispatch():
while True:
msg = await ws.receive()
if msg.type == aiohttp.WSMsgType.TEXT:
print('Text: ', msg.data.strip())
elif msg.type == aiohttp.WSMsgType.BINARY:
print('Binary: ', msg.data)
elif msg.type == aiohttp.WSMsgType.PING:
await ws.pong()
elif msg.type == aiohttp.WSMsgType.PONG:
print('Pong received')
else:
if msg.type == aiohttp.WSMsgType.CLOSE:
await ws.close()
elif msg.type == aiohttp.WSMsgType.ERROR:
print('Error during receive %s' % ws.exception())
elif msg.type == aiohttp.WSMsgType.CLOSED:
pass
break
await dispatch()
async def tick():
while True:
await (await queue.get())
async def main(url, loop):
await asyncio.wait([start_client(url, loop), tick()])
ARGS = argparse.ArgumentParser(
description="websocket console client for wssrv.py example.")
ARGS.add_argument(
'--host', action="store", dest='host',
default='127.0.0.1', help='Host name')
ARGS.add_argument(
'--port', action="store", dest='port',
default=8080, type=int, help='Port number')
if __name__ == '__main__':
args = ARGS.parse_args()
if ':' in args.host:
args.host, port = args.host.split(':', 1)
args.port = int(port)
url = 'http://{}:{}/ws/'.format(args.host, args.port)
loop = asyncio.get_event_loop()
loop.add_signal_handler(signal.SIGINT, loop.stop)
asyncio.Task(main(url, loop))
loop.run_forever()

View File

@ -0,0 +1,37 @@
use log::info;
use actix_files::Files;
use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws;
mod message;
mod server;
mod session;
use session::WsChatSession;
async fn chat_route(
req: HttpRequest,
stream: web::Payload,
) -> Result<HttpResponse, Error> {
ws::start(WsChatSession::default(), &req, stream)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
.init();
let addr = "127.0.0.1:8080";
let srv = HttpServer::new(move || {
App::new()
.service(web::resource("/ws/").to(chat_route))
.service(Files::new("/", "./static/").index_file("index.html"))
})
.bind(&addr)?;
info!("Starting http server: {}", &addr);
srv.run().await
}

View File

@ -0,0 +1,21 @@
use actix::prelude::*;
#[derive(Clone, Message)]
#[rtype(result = "()")]
pub struct ChatMessage(pub String);
#[derive(Clone, Message)]
#[rtype(result = "usize")]
pub struct JoinRoom(pub String, pub Option<String>, pub Recipient<ChatMessage>);
#[derive(Clone, Message)]
#[rtype(result = "()")]
pub struct LeaveRoom(pub String, pub usize);
#[derive(Clone, Message)]
#[rtype(result = "Vec<String>")]
pub struct ListRooms;
#[derive(Clone, Message)]
#[rtype(result = "()")]
pub struct SendMessage(pub String, pub usize, pub String);

View File

@ -0,0 +1,127 @@
use actix::prelude::*;
use actix_broker::BrokerSubscribe;
use std::collections::HashMap;
use std::mem;
use crate::message::{ChatMessage, JoinRoom, LeaveRoom, ListRooms, SendMessage};
type Client = Recipient<ChatMessage>;
type Room = HashMap<usize, Client>;
#[derive(Default)]
pub struct WsChatServer {
rooms: HashMap<String, Room>,
}
impl WsChatServer {
fn take_room(&mut self, room_name: &str) -> Option<Room> {
let room = self.rooms.get_mut(room_name)?;
let room = mem::replace(room, HashMap::new());
Some(room)
}
fn add_client_to_room(
&mut self,
room_name: &str,
id: Option<usize>,
client: Client,
) -> usize {
let mut id = id.unwrap_or_else(rand::random::<usize>);
if let Some(room) = self.rooms.get_mut(room_name) {
loop {
if room.contains_key(&id) {
id = rand::random::<usize>();
} else {
break;
}
}
room.insert(id, client);
return id;
}
// Create a new room for the first client
let mut room: Room = HashMap::new();
room.insert(id, client);
self.rooms.insert(room_name.to_owned(), room);
id
}
fn send_chat_message(
&mut self,
room_name: &str,
msg: &str,
_src: usize,
) -> Option<()> {
let mut room = self.take_room(room_name)?;
for (id, client) in room.drain() {
if client.do_send(ChatMessage(msg.to_owned())).is_ok() {
self.add_client_to_room(room_name, Some(id), client);
}
}
Some(())
}
}
impl Actor for WsChatServer {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
self.subscribe_system_async::<LeaveRoom>(ctx);
self.subscribe_system_async::<SendMessage>(ctx);
}
}
impl Handler<JoinRoom> for WsChatServer {
type Result = MessageResult<JoinRoom>;
fn handle(&mut self, msg: JoinRoom, _ctx: &mut Self::Context) -> Self::Result {
let JoinRoom(room_name, client_name, client) = msg;
let id = self.add_client_to_room(&room_name, None, client);
let join_msg = format!(
"{} joined {}",
client_name.unwrap_or_else(|| "anon".to_string()),
room_name
);
self.send_chat_message(&room_name, &join_msg, id);
MessageResult(id)
}
}
impl Handler<LeaveRoom> for WsChatServer {
type Result = ();
fn handle(&mut self, msg: LeaveRoom, _ctx: &mut Self::Context) {
if let Some(room) = self.rooms.get_mut(&msg.0) {
room.remove(&msg.1);
}
}
}
impl Handler<ListRooms> for WsChatServer {
type Result = MessageResult<ListRooms>;
fn handle(&mut self, _: ListRooms, _ctx: &mut Self::Context) -> Self::Result {
MessageResult(self.rooms.keys().cloned().collect())
}
}
impl Handler<SendMessage> for WsChatServer {
type Result = ();
fn handle(&mut self, msg: SendMessage, _ctx: &mut Self::Context) {
let SendMessage(room_name, id, msg) = msg;
self.send_chat_message(&room_name, &msg, id);
}
}
impl SystemService for WsChatServer {}
impl Supervised for WsChatServer {}

View File

@ -0,0 +1,161 @@
use log::{debug, info};
use actix::fut;
use actix::prelude::*;
use actix_broker::BrokerIssue;
use actix_web_actors::ws;
use crate::message::{ChatMessage, JoinRoom, LeaveRoom, ListRooms, SendMessage};
use crate::server::WsChatServer;
#[derive(Default)]
pub struct WsChatSession {
id: usize,
room: String,
name: Option<String>,
}
impl WsChatSession {
pub fn join_room(&mut self, room_name: &str, ctx: &mut ws::WebsocketContext<Self>) {
let room_name = room_name.to_owned();
// First send a leave message for the current room
let leave_msg = LeaveRoom(self.room.clone(), self.id);
// issue_sync comes from having the `BrokerIssue` trait in scope.
self.issue_system_sync(leave_msg, ctx);
// Then send a join message for the new room
let join_msg = JoinRoom(
room_name.to_owned(),
self.name.clone(),
ctx.address().recipient(),
);
WsChatServer::from_registry()
.send(join_msg)
.into_actor(self)
.then(|id, act, _ctx| {
if let Ok(id) = id {
act.id = id;
act.room = room_name;
}
fut::ready(())
})
.wait(ctx);
}
pub fn list_rooms(&mut self, ctx: &mut ws::WebsocketContext<Self>) {
WsChatServer::from_registry()
.send(ListRooms)
.into_actor(self)
.then(|res, _, ctx| {
if let Ok(rooms) = res {
for room in rooms {
ctx.text(room);
}
}
fut::ready(())
})
.wait(ctx);
}
pub fn send_msg(&self, msg: &str) {
let content = format!(
"{}: {}",
self.name.clone().unwrap_or_else(|| "anon".to_string()),
msg
);
let msg = SendMessage(self.room.clone(), self.id, content);
// issue_async comes from having the `BrokerIssue` trait in scope.
self.issue_system_async(msg);
}
}
impl Actor for WsChatSession {
type Context = ws::WebsocketContext<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
self.join_room("Main", ctx);
}
fn stopped(&mut self, _ctx: &mut Self::Context) {
info!(
"WsChatSession closed for {}({}) in room {}",
self.name.clone().unwrap_or_else(|| "anon".to_string()),
self.id,
self.room
);
}
}
impl Handler<ChatMessage> for WsChatSession {
type Result = ();
fn handle(&mut self, msg: ChatMessage, ctx: &mut Self::Context) {
ctx.text(msg.0);
}
}
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsChatSession {
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,
};
debug!("WEBSOCKET MESSAGE: {:?}", msg);
match msg {
ws::Message::Text(text) => {
let msg = text.trim();
if msg.starts_with('/') {
let mut command = msg.splitn(2, ' ');
match command.next() {
Some("/list") => self.list_rooms(ctx),
Some("/join") => {
if let Some(room_name) = command.next() {
self.join_room(room_name, ctx);
} else {
ctx.text("!!! room name is required");
}
}
Some("/name") => {
if let Some(name) = command.next() {
self.name = Some(name.to_owned());
ctx.text(format!("name changed to: {}", name));
} else {
ctx.text("!!! name is required");
}
}
_ => ctx.text(format!("!!! unknown command: {:?}", msg)),
}
return;
}
self.send_msg(msg);
}
ws::Message::Close(reason) => {
ctx.close(reason);
ctx.stop();
}
_ => {}
}
}
}

View File

@ -0,0 +1,204 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Websocket Chat Broker</title>
<style>
:root {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
font-size: 18px;
}
input[type='text'] {
font-size: inherit;
}
#log {
width: 30em;
height: 20em;
overflow: auto;
margin: 0.5em 0;
border: 1px solid black;
}
#status {
padding: 0 0.2em;
}
#text {
width: 17em;
padding: 0.5em;
}
.msg {
margin: 0;
padding: 0.25em 0.5em;
}
.msg--status {
/* a light yellow */
background-color: #ffffc9;
}
.msg--message {
/* a light blue */
background-color: #d2f4ff;
}
.msg--error {
background-color: pink;
}
</style>
</head>
<body>
<h1>Chat!</h1>
<div>
<button id="connect">Connect</button>
<span>Status:</span>
<span id="status">disconnected</span>
</div>
<div id="log"></div>
<form id="chatform">
<input type="text" id="text" />
<input type="submit" id="send" />
</form>
<hr />
<section>
<h2>Commands</h2>
<table style="border-spacing: 0.5em;">
<tr>
<td>
<code>/list</code>
</td>
<td>
list all available rooms
</td>
</tr>
<tr>
<td>
<code>/join name</code>
</td>
<td>
join room, if room does not exist, create new one
</td>
</tr>
<tr>
<td>
<code>/name name</code>
</td>
<td>
set session name
</td>
</tr>
<tr>
<td>
<code>some message</code>
</td>
<td>
just string, send message to all peers in same room
</td>
</tr>
</table>
</section>
<script>
const $status = document.querySelector('#status')
const $connectButton = document.querySelector('#connect')
const $log = document.querySelector('#log')
const $form = document.querySelector('#chatform')
const $input = document.querySelector('#text')
/** @type {WebSocket | null} */
var socket = null
function log(msg, type = 'status') {
$log.innerHTML += `<p class="msg msg--${type}">${msg}</p>`
$log.scrollTop += 1000
}
function connect() {
disconnect()
const { location } = window
const proto = location.protocol.startsWith('https') ? 'wss' : 'ws'
const wsUri = `${proto}://${location.host}/ws/`
log('Connecting...')
socket = new WebSocket(wsUri)
socket.onopen = () => {
log('Connected')
updateConnectionStatus()
}
socket.onmessage = (ev) => {
log('Received: ' + ev.data, 'message')
}
socket.onclose = () => {
log('Disconnected')
socket = null
updateConnectionStatus()
}
}
function disconnect() {
if (socket) {
log('Disconnecting...')
socket.close()
socket = null
updateConnectionStatus()
}
}
function updateConnectionStatus() {
if (socket) {
$status.style.backgroundColor = 'transparent'
$status.style.color = 'green'
$status.textContent = `connected`
$connectButton.innerHTML = 'Disconnect'
$input.focus()
} else {
$status.style.backgroundColor = 'red'
$status.style.color = 'white'
$status.textContent = 'disconnected'
$connectButton.textContent = 'Connect'
}
}
$connectButton.addEventListener('click', () => {
if (socket) {
disconnect()
} else {
connect()
}
updateConnectionStatus()
})
$form.addEventListener('submit', (ev) => {
ev.preventDefault()
const text = $input.value
log('Sending: ' + text)
socket.send(text)
$input.value = ''
$input.focus()
})
updateConnectionStatus()
</script>
</body>
</html>