mirror of
https://github.com/fafhrd91/actix-web
synced 2025-06-25 06:39:22 +02:00
process inactive tasks
This commit is contained in:
@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
|
||||
[[bin]]
|
||||
name = "websocket"
|
||||
name = "server"
|
||||
path = "src/main.rs"
|
||||
|
||||
[[bin]]
|
||||
@ -18,6 +18,7 @@ byteorder = "1.1"
|
||||
futures = "0.1"
|
||||
tokio-io = "0.1"
|
||||
tokio-core = "0.1"
|
||||
env_logger = "*"
|
||||
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
|
28
examples/websocket-chat/README.md
Normal file
28
examples/websocket-chat/README.md
Normal file
@ -0,0 +1,28 @@
|
||||
# Websocket chat example
|
||||
|
||||
This is extension of the
|
||||
[actix chat example](https://github.com/fafhrd91/actix/tree/master/examples/chat)
|
||||
|
||||
|
||||
## 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
|
||||
* `some message` - just string, send messsage 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 droppped
|
||||
|
||||
To start server use command: `cargo run --bin server`
|
||||
|
||||
## Client
|
||||
|
||||
Client connects to server. Reads input from stdin and sends to server.
|
||||
|
||||
To run client use command: `cargo run --bin client`
|
||||
|
||||
|
||||
## WebSocket Browser Client
|
||||
|
||||
Open url: http://localhost:8080/
|
72
examples/websocket-chat/client.py
Executable file
72
examples/websocket-chat/client.py
Executable 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()
|
@ -4,6 +4,7 @@ extern crate bytes;
|
||||
extern crate byteorder;
|
||||
extern crate tokio_io;
|
||||
extern crate tokio_core;
|
||||
extern crate env_logger;
|
||||
extern crate serde;
|
||||
extern crate serde_json;
|
||||
#[macro_use] extern crate serde_derive;
|
||||
@ -200,6 +201,7 @@ impl ResponseType<ws::Message> for WsChatSession {
|
||||
|
||||
|
||||
fn main() {
|
||||
let _ = env_logger::init();
|
||||
let sys = actix::System::new("websocket-example");
|
||||
|
||||
// Start chat server actor
|
||||
@ -218,7 +220,10 @@ fn main() {
|
||||
// redirect to websocket.html
|
||||
.resource("/", |r|
|
||||
r.handler(Method::GET, |req, payload, state| {
|
||||
httpcodes::HTTPOk
|
||||
httpcodes::HTTPFound
|
||||
.builder()
|
||||
.header("LOCATION", "/static/websocket.html")
|
||||
.body(Body::Empty)
|
||||
}))
|
||||
// websocket
|
||||
.resource("/ws/", |r| r.get::<WsChatSession>())
|
||||
|
72
examples/websocket/client.py
Executable file
72
examples/websocket/client.py
Executable 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()
|
Reference in New Issue
Block a user