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,15 @@
[package]
name = "websocket-autobahn"
version = "2.0.0"
authors = ["Mark Lodato <mlodato517@gmail.com"]
edition = "2018"
[[bin]]
name = "websocket-autobahn-server"
path = "src/main.rs"
[dependencies]
actix = "0.10"
actix-web = "3"
actix-web-actors = "3"
env_logger = "0.8"

View File

@ -0,0 +1,33 @@
# websocket
Websocket server for autobahn suite testing.
## Usage
### server
```bash
cd examples/websocket-autobahn
cargo run --bin websocket-autobahn-server
```
### Running Autobahn Test Suite
Running the autobahn test suite is easiest using the docker image
as explained on the [autobahn-testsuite repo](https://github.com/crossbario/autobahn-testsuite#using-the-testsuite-docker-image).
First, start a server (see above). Then, run the test suite in fuzzingclient mode:
```bash
docker run -it --rm \
-v "${PWD}/config:/config" \
-v "${PWD}/reports:/reports" \
--network host \
--name autobahn \
crossbario/autobahn-testsuite \
wstest \
--spec /config/fuzzingclient.json \
--mode fuzzingclient
```
Results are written to the `reports/servers` directory for viewing.

View File

@ -0,0 +1,15 @@
{
"outdir": "./reports/servers",
"servers": [
{
"agent": "actix-web-actors",
"url": "ws://host.docker.internal:9001"
}
],
"cases": ["*"],
"exclude-cases": [
"12.*",
"13.*"
],
"exclude-agent-cases": {}
}

View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,59 @@
use actix::prelude::*;
use actix_web::{middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws;
async fn ws_index(r: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
ws::start(WebSocket::new(), &r, stream)
}
struct WebSocket {}
impl Actor for WebSocket {
type Context = ws::WebsocketContext<Self>;
fn started(&mut self, _ctx: &mut Self::Context) {}
}
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WebSocket {
fn handle(
&mut self,
msg: Result<ws::Message, ws::ProtocolError>,
ctx: &mut Self::Context,
) {
if let Ok(msg) = msg {
match msg {
ws::Message::Text(text) => ctx.text(text),
ws::Message::Binary(bin) => ctx.binary(bin),
ws::Message::Ping(bytes) => ctx.pong(&bytes),
ws::Message::Close(reason) => {
ctx.close(reason);
ctx.stop();
}
_ => {}
}
} else {
ctx.stop();
}
}
}
impl WebSocket {
fn new() -> Self {
Self {}
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
env_logger::init();
HttpServer::new(|| {
App::new()
.wrap(middleware::Logger::default())
.service(web::resource("/").route(web::get().to(ws_index)))
})
.bind("127.0.0.1:9001")?
.run()
.await
}

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>

View File

@ -0,0 +1,23 @@
[package]
name = "websocket-example"
version = "2.0.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
edition = "2018"
[[bin]]
name = "websocket-chat-server"
path = "src/main.rs"
[dependencies]
actix = "0.10"
actix-web = "3"
actix-web-actors = "3"
actix-files = "0.3"
rand = "0.7"
bytes = "0.5"
byteorder = "1.3"
futures = "0.3"
env_logger = "0.8"
serde = "1"
serde_json = "1"

36
websockets/chat/README.md Normal file
View File

@ -0,0 +1,36 @@
# Websocket chat example
This is extension of the
[actix chat example](https://github.com/actix/actix/tree/master/examples/chat)
Added features:
* Browser WebSocket client
* Chat server runs in separate thread
* Tcp listener runs in separate thread
* Application state is shared with the websocket server and a resource at `/count/`
## Server
1. 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
* client has to send heartbeat `Ping` messages, if server does not receive a heartbeat message for 10 seconds connection gets dropped
2. [http://localhost:8080/count/](http://localhost:8080/count/) is a
non-websocket endpoint and will affect and display state.
To start server use command: `cargo run --bin websocket-chat-server`
## Client
Client connects to server. Reads input from stdin and sends to server.
To run client use command: `cargo run --bin websocket-chat-client`
## WebSocket Browser Client
Open url: [http://localhost:8080/](http://localhost:8080/)

80
websockets/chat/client.py Executable file
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()

264
websockets/chat/src/main.rs Normal file
View File

@ -0,0 +1,264 @@
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use std::time::{Duration, Instant};
use actix::*;
use actix_files as fs;
use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer, Responder};
use actix_web_actors::ws;
mod server;
/// How often heartbeat pings are sent
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
/// How long before lack of client response causes a timeout
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
/// Entry point for our websocket route
async fn chat_route(
req: HttpRequest,
stream: web::Payload,
srv: web::Data<Addr<server::ChatServer>>,
) -> Result<HttpResponse, Error> {
ws::start(
WsChatSession {
id: 0,
hb: Instant::now(),
room: "Main".to_owned(),
name: None,
addr: srv.get_ref().clone(),
},
&req,
stream,
)
}
/// Displays and affects state
async fn get_count(count: web::Data<Arc<AtomicUsize>>) -> impl Responder {
let current_count = count.fetch_add(1, Ordering::SeqCst);
format!("Visitors: {}", current_count)
}
struct WsChatSession {
/// unique session id
id: usize,
/// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT),
/// otherwise we drop connection.
hb: Instant,
/// joined room
room: String,
/// peer name
name: Option<String>,
/// Chat server
addr: Addr<server::ChatServer>,
}
impl Actor for WsChatSession {
type Context = ws::WebsocketContext<Self>;
/// Method is called on actor start.
/// We register ws session with ChatServer
fn started(&mut self, ctx: &mut Self::Context) {
// we'll start heartbeat process on session start.
self.hb(ctx);
// register self in chat server. `AsyncContext::wait` register
// future within context, but context waits until this future resolves
// before processing any other events.
// HttpContext::state() is instance of WsChatSessionState, state is shared
// across all routes within application
let addr = ctx.address();
self.addr
.send(server::Connect {
addr: addr.recipient(),
})
.into_actor(self)
.then(|res, act, ctx| {
match res {
Ok(res) => act.id = res,
// something is wrong with chat server
_ => ctx.stop(),
}
fut::ready(())
})
.wait(ctx);
}
fn stopping(&mut self, _: &mut Self::Context) -> Running {
// notify chat server
self.addr.do_send(server::Disconnect { id: self.id });
Running::Stop
}
}
/// Handle messages from chat server, we simply send it to peer websocket
impl Handler<server::Message> for WsChatSession {
type Result = ();
fn handle(&mut self, msg: server::Message, ctx: &mut Self::Context) {
ctx.text(msg.0);
}
}
/// WebSocket message handler
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,
};
println!("WEBSOCKET MESSAGE: {:?}", msg);
match msg {
ws::Message::Ping(msg) => {
self.hb = Instant::now();
ctx.pong(&msg);
}
ws::Message::Pong(_) => {
self.hb = Instant::now();
}
ws::Message::Text(text) => {
let m = text.trim();
// we check for /sss type of messages
if m.starts_with('/') {
let v: Vec<&str> = m.splitn(2, ' ').collect();
match v[0] {
"/list" => {
// Send ListRooms message to chat server and wait for
// response
println!("List rooms");
self.addr
.send(server::ListRooms)
.into_actor(self)
.then(|res, _, ctx| {
match res {
Ok(rooms) => {
for room in rooms {
ctx.text(room);
}
}
_ => println!("Something is wrong"),
}
fut::ready(())
})
.wait(ctx)
// .wait(ctx) pauses all events in context,
// so actor wont receive any new messages until it get list
// of rooms back
}
"/join" => {
if v.len() == 2 {
self.room = v[1].to_owned();
self.addr.do_send(server::Join {
id: self.id,
name: self.room.clone(),
});
ctx.text("joined");
} else {
ctx.text("!!! room name is required");
}
}
"/name" => {
if v.len() == 2 {
self.name = Some(v[1].to_owned());
} else {
ctx.text("!!! name is required");
}
}
_ => ctx.text(format!("!!! unknown command: {:?}", m)),
}
} else {
let msg = if let Some(ref name) = self.name {
format!("{}: {}", name, m)
} else {
m.to_owned()
};
// send message to chat server
self.addr.do_send(server::ClientMessage {
id: self.id,
msg,
room: self.room.clone(),
})
}
}
ws::Message::Binary(_) => println!("Unexpected binary"),
ws::Message::Close(reason) => {
ctx.close(reason);
ctx.stop();
}
ws::Message::Continuation(_) => {
ctx.stop();
}
ws::Message::Nop => (),
}
}
}
impl WsChatSession {
/// helper method that sends ping to client every second.
///
/// also this method checks heartbeats from client
fn hb(&self, ctx: &mut ws::WebsocketContext<Self>) {
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
// check client heartbeats
if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
// heartbeat timed out
println!("Websocket Client heartbeat failed, disconnecting!");
// notify chat server
act.addr.do_send(server::Disconnect { id: act.id });
// stop actor
ctx.stop();
// don't try to send a ping
return;
}
ctx.ping(b"");
});
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init();
// App state
// We are keeping a count of the number of visitors
let app_state = Arc::new(AtomicUsize::new(0));
// Start chat server actor
let server = server::ChatServer::new(app_state.clone()).start();
// Create Http server with websocket support
HttpServer::new(move || {
App::new()
.data(app_state.clone())
.data(server.clone())
// redirect to websocket.html
.service(web::resource("/").route(web::get().to(|| {
HttpResponse::Found()
.header("LOCATION", "/static/websocket.html")
.finish()
})))
.route("/count/", web::get().to(get_count))
// websocket
.service(web::resource("/ws/").to(chat_route))
// static resources
.service(fs::Files::new("/static/", "static/"))
})
.bind("127.0.0.1:8080")?
.run()
.await
}

View File

@ -0,0 +1,217 @@
//! `ChatServer` is an actor. It maintains list of connection client session.
//! And manages available rooms. Peers send messages to other peers in same
//! room through `ChatServer`.
use actix::prelude::*;
use rand::{self, rngs::ThreadRng, Rng};
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use std::collections::{HashMap, HashSet};
/// Chat server sends this messages to session
#[derive(Message)]
#[rtype(result = "()")]
pub struct Message(pub String);
/// Message for chat server communications
/// New chat session is created
#[derive(Message)]
#[rtype(usize)]
pub struct Connect {
pub addr: Recipient<Message>,
}
/// Session is disconnected
#[derive(Message)]
#[rtype(result = "()")]
pub struct Disconnect {
pub id: usize,
}
/// Send message to specific room
#[derive(Message)]
#[rtype(result = "()")]
pub struct ClientMessage {
/// Id of the client session
pub id: usize,
/// Peer message
pub msg: String,
/// Room name
pub room: String,
}
/// List of available rooms
pub struct ListRooms;
impl actix::Message for ListRooms {
type Result = Vec<String>;
}
/// Join room, if room does not exists create new one.
#[derive(Message)]
#[rtype(result = "()")]
pub struct Join {
/// Client id
pub id: usize,
/// Room name
pub name: String,
}
/// `ChatServer` manages chat rooms and responsible for coordinating chat
/// session. implementation is super primitive
pub struct ChatServer {
sessions: HashMap<usize, Recipient<Message>>,
rooms: HashMap<String, HashSet<usize>>,
rng: ThreadRng,
visitor_count: Arc<AtomicUsize>,
}
impl ChatServer {
pub fn new(visitor_count: Arc<AtomicUsize>) -> ChatServer {
// default room
let mut rooms = HashMap::new();
rooms.insert("Main".to_owned(), HashSet::new());
ChatServer {
sessions: HashMap::new(),
rooms,
rng: rand::thread_rng(),
visitor_count,
}
}
}
impl ChatServer {
/// Send message to all users in the room
fn send_message(&self, room: &str, message: &str, skip_id: usize) {
if let Some(sessions) = self.rooms.get(room) {
for id in sessions {
if *id != skip_id {
if let Some(addr) = self.sessions.get(id) {
let _ = addr.do_send(Message(message.to_owned()));
}
}
}
}
}
}
/// Make actor from `ChatServer`
impl Actor for ChatServer {
/// We are going to use simple Context, we just need ability to communicate
/// with other actors.
type Context = Context<Self>;
}
/// Handler for Connect message.
///
/// Register new session and assign unique id to this session
impl Handler<Connect> for ChatServer {
type Result = usize;
fn handle(&mut self, msg: Connect, _: &mut Context<Self>) -> Self::Result {
println!("Someone joined");
// notify all users in same room
self.send_message(&"Main".to_owned(), "Someone joined", 0);
// register session with random id
let id = self.rng.gen::<usize>();
self.sessions.insert(id, msg.addr);
// auto join session to Main room
self.rooms
.entry("Main".to_owned())
.or_insert_with(HashSet::new)
.insert(id);
let count = self.visitor_count.fetch_add(1, Ordering::SeqCst);
self.send_message("Main", &format!("Total visitors {}", count), 0);
// send id back
id
}
}
/// Handler for Disconnect message.
impl Handler<Disconnect> for ChatServer {
type Result = ();
fn handle(&mut self, msg: Disconnect, _: &mut Context<Self>) {
println!("Someone disconnected");
let mut rooms: Vec<String> = Vec::new();
// remove address
if self.sessions.remove(&msg.id).is_some() {
// remove session from all rooms
for (name, sessions) in &mut self.rooms {
if sessions.remove(&msg.id) {
rooms.push(name.to_owned());
}
}
}
// send message to other users
for room in rooms {
self.send_message(&room, "Someone disconnected", 0);
}
}
}
/// Handler for Message message.
impl Handler<ClientMessage> for ChatServer {
type Result = ();
fn handle(&mut self, msg: ClientMessage, _: &mut Context<Self>) {
self.send_message(&msg.room, msg.msg.as_str(), msg.id);
}
}
/// Handler for `ListRooms` message.
impl Handler<ListRooms> for ChatServer {
type Result = MessageResult<ListRooms>;
fn handle(&mut self, _: ListRooms, _: &mut Context<Self>) -> Self::Result {
let mut rooms = Vec::new();
for key in self.rooms.keys() {
rooms.push(key.to_owned())
}
MessageResult(rooms)
}
}
/// Join room, send disconnect message to old room
/// send join message to new room
impl Handler<Join> for ChatServer {
type Result = ();
fn handle(&mut self, msg: Join, _: &mut Context<Self>) {
let Join { id, name } = msg;
let mut rooms = Vec::new();
// remove session from all rooms
for (n, sessions) in &mut self.rooms {
if sessions.remove(&id) {
rooms.push(n.to_owned());
}
}
// send message to other users
for room in rooms {
self.send_message(&room, "Someone disconnected", 0);
}
self.rooms
.entry(name.clone())
.or_insert_with(HashSet::new)
.insert(id);
self.send_message(&name, "Someone connected", id);
}
}

View File

@ -0,0 +1,112 @@
<!DOCTYPE html>
<html>
<head>
<title>Chat!</title>
<meta charset="utf-8" />
<script>
'use strict'
window.onload = () => {
let conn = null
const log = (msg) => {
div_log.innerHTML += msg + '<br>'
div_log.scroll(0, div_log.scrollTop + 1000)
}
const connect = () => {
disconnect()
const wsUri =
(window.location.protocol === 'https:' ? 'wss://' : 'ws://') +
window.location.host +
'/ws/'
conn = new WebSocket(wsUri)
log('Connecting...')
conn.onopen = function () {
log('Connected.')
update_ui()
}
conn.onmessage = function (e) {
log('Received: ' + e.data)
}
conn.onclose = function () {
log('Disconnected.')
conn = null
update_ui()
}
}
const disconnect = () => {
if (conn) {
log('Disconnecting...')
conn.close()
conn = null
update_ui()
}
}
const update_ui = () => {
if (!conn) {
span_status.textContent = 'disconnected'
btn_connect.textContent = 'Connect'
} else {
span_status.textContent = `connected (${conn.protocol})`
btn_connect.textContent = 'Disconnect'
}
}
btn_connect.onclick = () => {
if (!conn) {
connect()
} else {
disconnect()
}
update_ui()
}
btn_send.onclick = () => {
if (!conn) return
const text = input_text.value
log('Sending: ' + text)
conn.send(text)
input_text.value = ''
input_text.focus()
}
input_text.onkeyup = (e) => {
if (e.key === 'Enter') {
btn_send.click()
}
}
}
</script>
</head>
<body>
<h3>Chat!</h3>
<div>
<button id="btn_connect">Connect</button>
Status: <span id="span_status">disconnected</span>
</div>
<div
id="div_log"
style="width: 20em; height: 15em; overflow: auto; border: 1px solid black"
></div>
<input id="input_text" type="text" />
<input id="btn_send" type="button" value="Send" />
</body>
</html>

View File

@ -0,0 +1,30 @@
[package]
name = "websocket-tcp-example"
version = "2.0.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
edition = "2018"
[[bin]]
name = "websocket-tcp-server"
path = "src/main.rs"
[[bin]]
name = "websocket-tcp-client"
path = "src/client.rs"
[dependencies]
actix = "0.10"
actix-web = "3"
actix-web-actors = "3"
actix-files = "0.3"
actix-codec = "0.3"
rand = "0.7"
bytes = "0.5.3"
byteorder = "1.2"
futures = "0.3"
env_logger = "0.8"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = "0.2.4"
tokio-util = "0.3"

View File

@ -0,0 +1,32 @@
# Websocket chat example
This is extension of the
[actix chat example](https://github.com/actix/actix/tree/master/examples/chat)
Added features:
* Browser WebSocket client
* Chat server runs in separate thread
* Tcp listener runs in separate 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
* client has to send heartbeat `Ping` messages, if server does not receive a heartbeat message for 10 seconds connection gets dropped
To start server use command: `cargo run --bin websocket-tcp-server`
## Client
Client connects to server. Reads input from stdin and sends to server.
To run client use command: `cargo run --bin websocket-tcp-client`
## WebSocket Browser Client
Open url: [http://localhost:8080/](http://localhost:8080/)

80
websockets/tcp-chat/client.py Executable file
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,139 @@
use actix::prelude::*;
use std::str::FromStr;
use std::time::Duration;
use std::{io, net, thread};
use tokio::io::{split, WriteHalf};
use tokio::net::TcpStream;
use tokio_util::codec::FramedRead;
mod codec;
#[actix_web::main]
async fn main() {
// Connect to server
let addr = net::SocketAddr::from_str("127.0.0.1:12345").unwrap();
println!("Running chat client");
let stream = TcpStream::connect(&addr).await.unwrap();
let addr = ChatClient::create(|ctx| {
let (r, w) = split(stream);
ChatClient::add_stream(FramedRead::new(r, codec::ClientChatCodec), ctx);
ChatClient {
framed: actix::io::FramedWrite::new(w, codec::ClientChatCodec, ctx),
}
});
// 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.do_send(ClientCommand(cmd));
});
}
struct ChatClient {
framed: actix::io::FramedWrite<
codec::ChatRequest,
WriteHalf<TcpStream>,
codec::ClientChatCodec,
>,
}
#[derive(Message)]
#[rtype(result = "()")]
struct ClientCommand(String);
impl Actor for ChatClient {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Context<Self>) {
// start heartbeats otherwise server will disconnect after 10 seconds
self.hb(ctx)
}
fn stopped(&mut self, _: &mut Context<Self>) {
println!("Disconnected");
// Stop application on disconnect
System::current().stop();
}
}
impl ChatClient {
fn hb(&self, ctx: &mut Context<Self>) {
ctx.run_later(Duration::new(1, 0), |act, ctx| {
act.framed.write(codec::ChatRequest::Ping);
act.hb(ctx);
// client should also check for a timeout here, similar to the
// server code
});
}
}
impl actix::io::WriteHandler<io::Error> for ChatClient {}
/// Handle stdin commands
impl Handler<ClientCommand> for ChatClient {
type Result = ();
fn handle(&mut self, msg: ClientCommand, _: &mut Context<Self>) {
let m = msg.0.trim();
if m.is_empty() {
return;
}
// we check for /sss type of messages
if m.starts_with('/') {
let v: Vec<&str> = m.splitn(2, ' ').collect();
match v[0] {
"/list" => {
self.framed.write(codec::ChatRequest::List);
}
"/join" => {
if v.len() == 2 {
self.framed.write(codec::ChatRequest::Join(v[1].to_owned()));
} else {
println!("!!! room name is required");
}
}
_ => println!("!!! unknown command"),
}
} else {
self.framed.write(codec::ChatRequest::Message(m.to_owned()));
}
}
}
/// Server communication
impl StreamHandler<Result<codec::ChatResponse, io::Error>> for ChatClient {
fn handle(
&mut self,
msg: Result<codec::ChatResponse, io::Error>,
ctx: &mut Context<Self>,
) {
match msg {
Ok(codec::ChatResponse::Message(ref msg)) => {
println!("message: {}", msg);
}
Ok(codec::ChatResponse::Joined(ref msg)) => {
println!("!!! joined: {}", msg);
}
Ok(codec::ChatResponse::Rooms(rooms)) => {
println!("\n!!! Available rooms:");
for room in rooms {
println!("{}", room);
}
println!();
}
_ => ctx.stop(),
}
}
}

View File

@ -0,0 +1,129 @@
#![allow(dead_code)]
use std::io;
use actix::prelude::*;
use actix_codec::{Decoder, Encoder};
use byteorder::{BigEndian, ByteOrder};
use bytes::{BufMut, BytesMut};
use serde::{Deserialize, Serialize};
use serde_json as json;
/// Client request
#[derive(Serialize, Deserialize, Debug, Message)]
#[rtype(result = "()")]
#[serde(tag = "cmd", content = "data")]
pub enum ChatRequest {
/// List rooms
List,
/// Join rooms
Join(String),
/// Send message
Message(String),
/// Ping
Ping,
}
/// Server response
#[derive(Serialize, Deserialize, Debug, Message)]
#[rtype(result = "()")]
#[serde(tag = "cmd", content = "data")]
pub enum ChatResponse {
Ping,
/// List of rooms
Rooms(Vec<String>),
/// Joined
Joined(String),
/// Message
Message(String),
}
/// Codec for Client -> Server transport
pub struct ChatCodec;
impl Decoder for ChatCodec {
type Item = ChatRequest;
type Error = io::Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
let size = {
if src.len() < 2 {
return Ok(None);
}
BigEndian::read_u16(src.as_ref()) as usize
};
if src.len() >= size + 2 {
let _ = src.split_to(2);
let buf = src.split_to(size);
Ok(Some(json::from_slice::<ChatRequest>(&buf)?))
} else {
Ok(None)
}
}
}
impl Encoder<ChatResponse> for ChatCodec {
type Error = io::Error;
fn encode(
&mut self,
msg: ChatResponse,
dst: &mut BytesMut,
) -> Result<(), Self::Error> {
let msg = json::to_string(&msg).unwrap();
let msg_ref: &[u8] = msg.as_ref();
dst.reserve(msg_ref.len() + 2);
dst.put_u16(msg_ref.len() as u16);
dst.put(msg_ref);
Ok(())
}
}
/// Codec for Server -> Client transport
pub struct ClientChatCodec;
impl Decoder for ClientChatCodec {
type Item = ChatResponse;
type Error = io::Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
let size = {
if src.len() < 2 {
return Ok(None);
}
BigEndian::read_u16(src.as_ref()) as usize
};
if src.len() >= size + 2 {
let _ = src.split_to(2);
let buf = src.split_to(size);
Ok(Some(json::from_slice::<ChatResponse>(&buf)?))
} else {
Ok(None)
}
}
}
impl Encoder<ChatRequest> for ClientChatCodec {
type Error = io::Error;
fn encode(
&mut self,
msg: ChatRequest,
dst: &mut BytesMut,
) -> Result<(), Self::Error> {
let msg = json::to_string(&msg).unwrap();
let msg_ref: &[u8] = msg.as_ref();
dst.reserve(msg_ref.len() + 2);
dst.put_u16(msg_ref.len() as u16);
dst.put(msg_ref);
Ok(())
}
}

View File

@ -0,0 +1,253 @@
use std::time::{Duration, Instant};
use actix::*;
use actix_files as fs;
use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws;
mod codec;
mod server;
mod session;
/// How often heartbeat pings are sent
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
/// How long before lack of client response causes a timeout
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
/// Entry point for our route
async fn chat_route(
req: HttpRequest,
stream: web::Payload,
srv: web::Data<Addr<server::ChatServer>>,
) -> Result<HttpResponse, Error> {
ws::start(
WsChatSession {
id: 0,
hb: Instant::now(),
room: "Main".to_owned(),
name: None,
addr: srv.get_ref().clone(),
},
&req,
stream,
)
}
struct WsChatSession {
/// unique session id
id: usize,
/// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT),
/// otherwise we drop connection.
hb: Instant,
/// joined room
room: String,
/// peer name
name: Option<String>,
/// Chat server
addr: Addr<server::ChatServer>,
}
impl Actor for WsChatSession {
type Context = ws::WebsocketContext<Self>;
/// Method is called on actor start.
/// We register ws session with ChatServer
fn started(&mut self, ctx: &mut Self::Context) {
// we'll start heartbeat process on session start.
self.hb(ctx);
// register self in chat server. `AsyncContext::wait` register
// future within context, but context waits until this future resolves
// before processing any other events.
// HttpContext::state() is instance of WsChatSessionState, state is shared
// across all routes within application
let addr = ctx.address();
self.addr
.send(server::Connect {
addr: addr.recipient(),
})
.into_actor(self)
.then(|res, act, ctx| {
match res {
Ok(res) => act.id = res,
// something is wrong with chat server
_ => ctx.stop(),
}
fut::ready(())
})
.wait(ctx);
}
fn stopping(&mut self, _: &mut Self::Context) -> Running {
// notify chat server
self.addr.do_send(server::Disconnect { id: self.id });
Running::Stop
}
}
/// Handle messages from chat server, we simply send it to peer websocket
impl Handler<session::Message> for WsChatSession {
type Result = ();
fn handle(&mut self, msg: session::Message, ctx: &mut Self::Context) {
ctx.text(msg.0);
}
}
/// WebSocket message handler
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,
};
println!("WEBSOCKET MESSAGE: {:?}", msg);
match msg {
ws::Message::Ping(msg) => {
self.hb = Instant::now();
ctx.pong(&msg);
}
ws::Message::Pong(_) => {
self.hb = Instant::now();
}
ws::Message::Text(text) => {
let m = text.trim();
// we check for /sss type of messages
if m.starts_with('/') {
let v: Vec<&str> = m.splitn(2, ' ').collect();
match v[0] {
"/list" => {
// Send ListRooms message to chat server and wait for
// response
println!("List rooms");
self.addr
.send(server::ListRooms)
.into_actor(self)
.then(|res, _, ctx| {
match res {
Ok(rooms) => {
for room in rooms {
ctx.text(room);
}
}
_ => println!("Something is wrong"),
}
fut::ready(())
})
.wait(ctx)
// .wait(ctx) pauses all events in context,
// so actor wont receive any new messages until it get list
// of rooms back
}
"/join" => {
if v.len() == 2 {
self.room = v[1].to_owned();
self.addr.do_send(server::Join {
id: self.id,
name: self.room.clone(),
});
ctx.text("joined");
} else {
ctx.text("!!! room name is required");
}
}
"/name" => {
if v.len() == 2 {
self.name = Some(v[1].to_owned());
} else {
ctx.text("!!! name is required");
}
}
_ => ctx.text(format!("!!! unknown command: {:?}", m)),
}
} else {
let msg = if let Some(ref name) = self.name {
format!("{}: {}", name, m)
} else {
m.to_owned()
};
// send message to chat server
self.addr.do_send(server::Message {
id: self.id,
msg,
room: self.room.clone(),
})
}
}
ws::Message::Binary(_) => println!("Unexpected binary"),
ws::Message::Close(reason) => {
ctx.close(reason);
ctx.stop();
}
_ => (),
}
}
}
impl WsChatSession {
/// helper method that sends ping to client every second.
///
/// also this method checks heartbeats from client
fn hb(&self, ctx: &mut ws::WebsocketContext<Self>) {
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
// check client heartbeats
if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
// heartbeat timed out
println!("Websocket Client heartbeat failed, disconnecting!");
// notify chat server
act.addr.do_send(server::Disconnect { id: act.id });
// stop actor
ctx.stop();
// don't try to send a ping
return;
}
ctx.ping(b"");
});
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init();
// Start chat server actor
let server = server::ChatServer::default().start();
// Start tcp server in separate thread
let srv = server.clone();
session::tcp_server("127.0.0.1:12345", srv);
println!("Started http server: 127.0.0.1:8080");
// Create Http server with websocket support
HttpServer::new(move || {
App::new()
.data(server.clone())
// redirect to websocket.html
.service(web::resource("/").route(web::get().to(|| {
HttpResponse::Found()
.header("LOCATION", "/static/websocket.html")
.finish()
})))
// websocket
.service(web::resource("/ws/").to(chat_route))
// static resources
.service(fs::Files::new("/static/", "static/"))
})
.bind("127.0.0.1:8080")?
.run()
.await
}

View File

@ -0,0 +1,199 @@
//! `ChatServer` is an actor. It maintains list of connection client session.
//! And manages available rooms. Peers send messages to other peers in same
//! room through `ChatServer`.
use actix::prelude::*;
use rand::{self, rngs::ThreadRng, Rng};
use std::collections::{HashMap, HashSet};
use crate::session;
/// Message for chat server communications
/// New chat session is created
#[derive(Message)]
#[rtype(usize)]
pub struct Connect {
pub addr: Recipient<session::Message>,
}
/// Session is disconnected
#[derive(Message)]
#[rtype(result = "()")]
pub struct Disconnect {
pub id: usize,
}
/// Send message to specific room
#[derive(Message)]
#[rtype(result = "()")]
pub struct Message {
/// Id of the client session
pub id: usize,
/// Peer message
pub msg: String,
/// Room name
pub room: String,
}
/// List of available rooms
pub struct ListRooms;
impl actix::Message for ListRooms {
type Result = Vec<String>;
}
/// Join room, if room does not exists create new one.
#[derive(Message)]
#[rtype(result = "()")]
pub struct Join {
/// Client id
pub id: usize,
/// Room name
pub name: String,
}
/// `ChatServer` manages chat rooms and responsible for coordinating chat
/// session. implementation is super primitive
pub struct ChatServer {
sessions: HashMap<usize, Recipient<session::Message>>,
rooms: HashMap<String, HashSet<usize>>,
rng: ThreadRng,
}
impl Default for ChatServer {
fn default() -> ChatServer {
// default room
let mut rooms = HashMap::new();
rooms.insert("Main".to_owned(), HashSet::new());
ChatServer {
sessions: HashMap::new(),
rooms,
rng: rand::thread_rng(),
}
}
}
impl ChatServer {
/// Send message to all users in the room
fn send_message(&self, room: &str, message: &str, skip_id: usize) {
if let Some(sessions) = self.rooms.get(room) {
for id in sessions {
if *id != skip_id {
if let Some(addr) = self.sessions.get(id) {
let _ = addr.do_send(session::Message(message.to_owned()));
}
}
}
}
}
}
/// Make actor from `ChatServer`
impl Actor for ChatServer {
/// We are going to use simple Context, we just need ability to communicate
/// with other actors.
type Context = Context<Self>;
}
/// Handler for Connect message.
///
/// Register new session and assign unique id to this session
impl Handler<Connect> for ChatServer {
type Result = usize;
fn handle(&mut self, msg: Connect, _: &mut Context<Self>) -> Self::Result {
println!("Someone joined");
// notify all users in same room
self.send_message(&"Main".to_owned(), "Someone joined", 0);
// register session with random id
let id = self.rng.gen::<usize>();
self.sessions.insert(id, msg.addr);
// auto join session to Main room
self.rooms.get_mut(&"Main".to_owned()).unwrap().insert(id);
// send id back
id
}
}
/// Handler for Disconnect message.
impl Handler<Disconnect> for ChatServer {
type Result = ();
fn handle(&mut self, msg: Disconnect, _: &mut Context<Self>) {
println!("Someone disconnected");
let mut rooms: Vec<String> = Vec::new();
// remove address
if self.sessions.remove(&msg.id).is_some() {
// remove session from all rooms
for (name, sessions) in &mut self.rooms {
if sessions.remove(&msg.id) {
rooms.push(name.to_owned());
}
}
}
// send message to other users
for room in rooms {
self.send_message(&room, "Someone disconnected", 0);
}
}
}
/// Handler for Message message.
impl Handler<Message> for ChatServer {
type Result = ();
fn handle(&mut self, msg: Message, _: &mut Context<Self>) {
self.send_message(&msg.room, msg.msg.as_str(), msg.id);
}
}
/// Handler for `ListRooms` message.
impl Handler<ListRooms> for ChatServer {
type Result = MessageResult<ListRooms>;
fn handle(&mut self, _: ListRooms, _: &mut Context<Self>) -> Self::Result {
let mut rooms = Vec::new();
for key in self.rooms.keys() {
rooms.push(key.to_owned())
}
MessageResult(rooms)
}
}
/// Join room, send disconnect message to old room
/// send join message to new room
impl Handler<Join> for ChatServer {
type Result = ();
fn handle(&mut self, msg: Join, _: &mut Context<Self>) {
let Join { id, name } = msg;
let mut rooms = Vec::new();
// remove session from all rooms
for (n, sessions) in &mut self.rooms {
if sessions.remove(&id) {
rooms.push(n.to_owned());
}
}
// send message to other users
for room in rooms {
self.send_message(&room, "Someone disconnected", 0);
}
if self.rooms.get_mut(&name).is_none() {
self.rooms.insert(name.clone(), HashSet::new());
}
self.send_message(&name, "Someone connected", id);
self.rooms.get_mut(&name).unwrap().insert(id);
}
}

View File

@ -0,0 +1,201 @@
//! `ClientSession` is an actor, it manages peer tcp connection and
//! proxies commands from peer to `ChatServer`.
use std::str::FromStr;
use std::time::{Duration, Instant};
use std::{io, net};
use futures::StreamExt;
use tokio::io::{split, WriteHalf};
use tokio::net::{TcpListener, TcpStream};
use tokio_util::codec::FramedRead;
use actix::prelude::*;
use crate::codec::{ChatCodec, ChatRequest, ChatResponse};
use crate::server::{self, ChatServer};
/// Chat server sends this messages to session
#[derive(Message)]
#[rtype(result = "()")]
pub struct Message(pub String);
/// `ChatSession` actor is responsible for tcp peer communications.
pub struct ChatSession {
/// unique session id
id: usize,
/// this is address of chat server
addr: Addr<ChatServer>,
/// Client must send ping at least once per 10 seconds, otherwise we drop
/// connection.
hb: Instant,
/// joined room
room: String,
/// Framed wrapper
framed: actix::io::FramedWrite<ChatResponse, WriteHalf<TcpStream>, ChatCodec>,
}
impl Actor for ChatSession {
/// For tcp communication we are going to use `FramedContext`.
/// It is convenient wrapper around `Framed` object from `tokio_io`
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
// we'll start heartbeat process on session start.
self.hb(ctx);
// 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 = ctx.address();
self.addr
.send(server::Connect {
addr: addr.recipient(),
})
.into_actor(self)
.then(|res, act, ctx| {
match res {
Ok(res) => act.id = res,
// something is wrong with chat server
_ => ctx.stop(),
}
actix::fut::ready(())
})
.wait(ctx);
}
fn stopping(&mut self, _: &mut Self::Context) -> Running {
// notify chat server
self.addr.do_send(server::Disconnect { id: self.id });
Running::Stop
}
}
impl actix::io::WriteHandler<io::Error> for ChatSession {}
/// To use `Framed` we have to define Io type and Codec
impl StreamHandler<Result<ChatRequest, io::Error>> for ChatSession {
/// This is main event loop for client requests
fn handle(&mut self, msg: Result<ChatRequest, io::Error>, ctx: &mut Context<Self>) {
match msg {
Ok(ChatRequest::List) => {
// Send ListRooms message to chat server and wait for response
println!("List rooms");
self.addr
.send(server::ListRooms)
.into_actor(self)
.then(|res, act, _| {
match res {
Ok(rooms) => {
act.framed.write(ChatResponse::Rooms(rooms));
}
_ => println!("Something is wrong"),
}
actix::fut::ready(())
})
.wait(ctx)
// .wait(ctx) pauses all events in context,
// so actor wont receive any new messages until it get list of rooms back
}
Ok(ChatRequest::Join(name)) => {
println!("Join to room: {}", name);
self.room = name.clone();
self.addr.do_send(server::Join {
id: self.id,
name: name.clone(),
});
self.framed.write(ChatResponse::Joined(name));
}
Ok(ChatRequest::Message(message)) => {
// send message to chat server
println!("Peer message: {}", message);
self.addr.do_send(server::Message {
id: self.id,
msg: message,
room: self.room.clone(),
})
}
// we update heartbeat time on ping from peer
Ok(ChatRequest::Ping) => self.hb = Instant::now(),
_ => ctx.stop(),
}
}
}
/// Handler for Message, chat server sends this message, we just send string to
/// peer
impl Handler<Message> for ChatSession {
type Result = ();
fn handle(&mut self, msg: Message, _: &mut Context<Self>) {
// send message to peer
self.framed.write(ChatResponse::Message(msg.0));
}
}
/// Helper methods
impl ChatSession {
pub fn new(
addr: Addr<ChatServer>,
framed: actix::io::FramedWrite<ChatResponse, WriteHalf<TcpStream>, ChatCodec>,
) -> ChatSession {
ChatSession {
id: 0,
addr,
hb: Instant::now(),
room: "Main".to_owned(),
framed,
}
}
/// helper method that sends ping to client every second.
///
/// also this method check heartbeats from client
fn hb(&self, ctx: &mut Context<Self>) {
ctx.run_interval(Duration::new(1, 0), |act, ctx| {
// check client heartbeats
if Instant::now().duration_since(act.hb) > Duration::new(10, 0) {
// heartbeat timed out
println!("Client heartbeat failed, disconnecting!");
// notify chat server
act.addr.do_send(server::Disconnect { id: act.id });
// stop actor
ctx.stop();
}
act.framed.write(ChatResponse::Ping);
// if we can not send message to sink, sink is closed (disconnected)
});
}
}
/// Define tcp server that will accept incoming tcp connection and create
/// chat actors.
pub fn tcp_server(_s: &str, server: Addr<ChatServer>) {
// Create server listener
let addr = net::SocketAddr::from_str("127.0.0.1:12345").unwrap();
actix_web::rt::spawn(async move {
let server = server.clone();
let mut listener = TcpListener::bind(&addr).await.unwrap();
let mut incoming = listener.incoming();
while let Some(stream) = incoming.next().await {
match stream {
Ok(stream) => {
let server = server.clone();
ChatSession::create(|ctx| {
let (r, w) = split(stream);
ChatSession::add_stream(FramedRead::new(r, ChatCodec), ctx);
ChatSession::new(
server,
actix::io::FramedWrite::new(w, ChatCodec, ctx),
)
});
}
Err(_) => return,
}
}
});
}

View File

@ -0,0 +1,90 @@
<!DOCTYPE html>
<meta charset="utf-8" />
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script language="javascript" type="text/javascript">
$(function() {
var conn = null;
function log(msg) {
var control = $('#log');
control.html(control.html() + msg + '<br/>');
control.scrollTop(control.scrollTop() + 1000);
}
function connect() {
disconnect();
var wsUri = (window.location.protocol=='https:'&&'wss://'||'ws://')+window.location.host + '/ws/';
conn = new WebSocket(wsUri);
log('Connecting...');
conn.onopen = function() {
log('Connected.');
update_ui();
};
conn.onmessage = function(e) {
log('Received: ' + e.data);
};
conn.onclose = function() {
log('Disconnected.');
conn = null;
update_ui();
};
}
function disconnect() {
if (conn != null) {
log('Disconnecting...');
conn.close();
conn = null;
update_ui();
}
}
function update_ui() {
var msg = '';
if (conn == null) {
$('#status').text('disconnected');
$('#connect').html('Connect');
} else {
$('#status').text('connected (' + conn.protocol + ')');
$('#connect').html('Disconnect');
}
}
$('#connect').click(function() {
if (conn == null) {
connect();
} else {
disconnect();
}
update_ui();
return false;
});
$('#send').click(function() {
var text = $('#text').val();
log('Sending: ' + text);
conn.send(text);
$('#text').val('').focus();
return false;
});
$('#text').keyup(function(e) {
if (e.keyCode === 13) {
$('#send').click();
return false;
}
});
});
</script>
</head>
<body>
<h3>Chat!</h3>
<div>
<button id="connect">Connect</button>&nbsp;|&nbsp;Status:
<span id="status">disconnected</span>
</div>
<div id="log"
style="width:20em;height:15em;overflow:auto;border:1px solid black">
</div>
<form id="chatform" onsubmit="return false;">
<input id="text" type="text" />
<input id="send" type="button" value="Send" />
</form>
</body>
</html>

View File

@ -0,0 +1,24 @@
[package]
name = "websocket"
version = "2.0.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
edition = "2018"
[[bin]]
name = "websocket-server"
path = "src/main.rs"
[[bin]]
name = "websocket-client"
path = "src/client.rs"
[dependencies]
actix = "0.10"
actix-codec = "0.3"
actix-web = "3"
actix-web-actors = "3"
actix-files = "0.3"
awc = "2"
env_logger = "0.8"
futures = "0.3.1"
bytes = "0.5.3"

View File

@ -0,0 +1,34 @@
# websocket
Simple echo websocket server.
## Usage
### server
```bash
cd examples/websocket
cargo run --bin websocket-server
# Started http server: 127.0.0.1:8080
```
### web client
- [http://localhost:8080/index.html](http://localhost:8080/index.html)
### rust client
```bash
cd examples/websocket
cargo run --bin websocket-client
```
### python client
- ``pip install aiohttp``
- ``python websocket-client.py``
if ubuntu :
- ``pip3 install aiohttp``
- ``python3 websocket-client.py``

View File

@ -0,0 +1,113 @@
//! Simple websocket client.
use std::time::Duration;
use std::{io, thread};
use actix::io::SinkWrite;
use actix::*;
use actix_codec::Framed;
use awc::{
error::WsProtocolError,
ws::{Codec, Frame, Message},
BoxedSocket, Client,
};
use bytes::Bytes;
use futures::stream::{SplitSink, StreamExt};
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
let sys = System::new("websocket-client");
Arbiter::spawn(async {
let (response, framed) = Client::new()
.ws("http://127.0.0.1:8080/ws/")
.connect()
.await
.map_err(|e| {
println!("Error: {}", e);
})
.unwrap();
println!("{:?}", response);
let (sink, stream) = framed.split();
let addr = ChatClient::create(|ctx| {
ChatClient::add_stream(stream, ctx);
ChatClient(SinkWrite::new(sink, ctx))
});
// 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.do_send(ClientCommand(cmd));
});
});
sys.run().unwrap();
}
struct ChatClient(SinkWrite<Message, SplitSink<Framed<BoxedSocket, Codec>, Message>>);
#[derive(Message)]
#[rtype(result = "()")]
struct ClientCommand(String);
impl Actor for ChatClient {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Context<Self>) {
// start heartbeats otherwise server will disconnect after 10 seconds
self.hb(ctx)
}
fn stopped(&mut self, _: &mut Context<Self>) {
println!("Disconnected");
// Stop application on disconnect
System::current().stop();
}
}
impl ChatClient {
fn hb(&self, ctx: &mut Context<Self>) {
ctx.run_later(Duration::new(1, 0), |act, ctx| {
act.0.write(Message::Ping(Bytes::from_static(b"")));
act.hb(ctx);
// client should also check for a timeout here, similar to the
// server code
});
}
}
/// Handle stdin commands
impl Handler<ClientCommand> for ChatClient {
type Result = ();
fn handle(&mut self, msg: ClientCommand, _ctx: &mut Context<Self>) {
self.0.write(Message::Text(msg.0));
}
}
/// Handle server websocket messages
impl StreamHandler<Result<Frame, WsProtocolError>> for ChatClient {
fn handle(&mut self, msg: Result<Frame, WsProtocolError>, _: &mut Context<Self>) {
if let Ok(Frame::Text(txt)) = msg {
println!("Server: {:?}", txt)
}
}
fn started(&mut self, _ctx: &mut Context<Self>) {
println!("Connected");
}
fn finished(&mut self, ctx: &mut Context<Self>) {
println!("Server disconnected");
ctx.stop()
}
}
impl actix::io::WriteHandler<WsProtocolError> for ChatClient {}

View File

@ -0,0 +1,116 @@
//! Simple echo websocket server.
//! Open `http://localhost:8080/ws/index.html` in browser
//! or [python console client](https://github.com/actix/examples/blob/master/websocket/websocket-client.py)
//! could be used for testing.
use std::time::{Duration, Instant};
use actix::prelude::*;
use actix_files as fs;
use actix_web::{middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws;
/// How often heartbeat pings are sent
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
/// How long before lack of client response causes a timeout
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
/// do websocket handshake and start `MyWebSocket` actor
async fn ws_index(r: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
println!("{:?}", r);
let res = ws::start(MyWebSocket::new(), &r, stream);
println!("{:?}", res);
res
}
/// websocket connection is long running connection, it easier
/// to handle with an actor
struct MyWebSocket {
/// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT),
/// otherwise we drop connection.
hb: Instant,
}
impl Actor for MyWebSocket {
type Context = ws::WebsocketContext<Self>;
/// Method is called on actor start. We start the heartbeat process here.
fn started(&mut self, ctx: &mut Self::Context) {
self.hb(ctx);
}
}
/// Handler for `ws::Message`
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWebSocket {
fn handle(
&mut self,
msg: Result<ws::Message, ws::ProtocolError>,
ctx: &mut Self::Context,
) {
// process websocket messages
println!("WS: {:?}", msg);
match msg {
Ok(ws::Message::Ping(msg)) => {
self.hb = Instant::now();
ctx.pong(&msg);
}
Ok(ws::Message::Pong(_)) => {
self.hb = Instant::now();
}
Ok(ws::Message::Text(text)) => ctx.text(text),
Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
Ok(ws::Message::Close(reason)) => {
ctx.close(reason);
ctx.stop();
}
_ => ctx.stop(),
}
}
}
impl MyWebSocket {
fn new() -> Self {
Self { hb: Instant::now() }
}
/// helper method that sends ping to client every second.
///
/// also this method checks heartbeats from client
fn hb(&self, ctx: &mut <Self as Actor>::Context) {
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
// check client heartbeats
if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
// heartbeat timed out
println!("Websocket Client heartbeat failed, disconnecting!");
// stop actor
ctx.stop();
// don't try to send a ping
return;
}
ctx.ping(b"");
});
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
env_logger::init();
HttpServer::new(|| {
App::new()
// enable logger
.wrap(middleware::Logger::default())
// websocket route
.service(web::resource("/ws/").route(web::get().to(ws_index)))
// static files
.service(fs::Files::new("/", "static/").index_file("index.html"))
})
// start http server on 127.0.0.1:8080
.bind("127.0.0.1:8080")?
.run()
.await
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

View File

@ -0,0 +1,90 @@
<!DOCTYPE html>
<meta charset="utf-8" />
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script language="javascript" type="text/javascript">
$(function() {
var conn = null;
function log(msg) {
var control = $('#log');
control.html(control.html() + msg + '<br/>');
control.scrollTop(control.scrollTop() + 1000);
}
function connect() {
disconnect();
var wsUri = (window.location.protocol=='https:'&&'wss://'||'ws://')+window.location.host + '/ws/';
conn = new WebSocket(wsUri);
log('Connecting...');
conn.onopen = function() {
log('Connected.');
update_ui();
};
conn.onmessage = function(e) {
log('Received: ' + e.data);
};
conn.onclose = function() {
log('Disconnected.');
conn = null;
update_ui();
};
}
function disconnect() {
if (conn != null) {
log('Disconnecting...');
conn.close();
conn = null;
update_ui();
}
}
function update_ui() {
var msg = '';
if (conn == null) {
$('#status').text('disconnected');
$('#connect').html('Connect');
} else {
$('#status').text('connected (' + conn.protocol + ')');
$('#connect').html('Disconnect');
}
}
$('#connect').click(function() {
if (conn == null) {
connect();
} else {
disconnect();
}
update_ui();
return false;
});
$('#send').click(function() {
var text = $('#text').val();
log('Sending: ' + text);
conn.send(text);
$('#text').val('').focus();
return false;
});
$('#text').keyup(function(e) {
if (e.keyCode === 13) {
$('#send').click();
return false;
}
});
});
</script>
</head>
<body>
<h3>Chat!</h3>
<div>
<button id="connect">Connect</button>&nbsp;|&nbsp;Status:
<span id="status">disconnected</span>
</div>
<div id="log"
style="width:20em;height:15em;overflow:auto;border:1px solid black">
</div>
<form id="chatform" onsubmit="return false;">
<input id="text" type="text" />
<input id="send" type="button" value="Send" />
</form>
</body>
</html>

View File

@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""websocket cmd client for wssrv.py example."""
import argparse
import asyncio
import signal
import sys
import aiohttp
def start_client(loop, url):
name = input('Please enter your name: ')
# send request
ws = yield from aiohttp.ClientSession().ws_connect(url, autoclose=False, autoping=False)
# input reader
def stdin_callback():
line = sys.stdin.buffer.readline().decode('utf-8')
if not line:
loop.stop()
else:
ws.send_str(name + ': ' + line)
loop.add_reader(sys.stdin.fileno(), stdin_callback)
@asyncio.coroutine
def dispatch():
while True:
msg = yield from 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:
ws.pong()
elif msg.type == aiohttp.WSMsgType.PONG:
print('Pong received')
else:
if msg.type == aiohttp.WSMsgType.CLOSE:
yield from ws.close()
elif msg.type == aiohttp.WSMsgType.ERROR:
print('Error during receive %s' % ws.exception())
elif msg.type == aiohttp.WSMsgType.CLOSED:
pass
break
yield from dispatch()
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(start_client(loop, url))
loop.run_forever()