Skip to content

Commit

Permalink
Initial commit, mostly working client
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexey Galakhov committed Jan 30, 2017
0 parents commit e63f594
Show file tree
Hide file tree
Showing 19 changed files with 2,549 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
@@ -0,0 +1,2 @@
target
Cargo.lock
24 changes: 24 additions & 0 deletions Cargo.toml
@@ -0,0 +1,24 @@
[package]
name = "ws2"
version = "0.1.0"
authors = ["Alexey Galakhov"]

[features]
default = []
tls = ["native-tls"]

[dependencies]
base64 = "*"
byteorder = "*"
bytes = { git = "https://github.com/carllerche/bytes.git" }
httparse = "*"
env_logger = "*"
log = "*"
rand = "*"
sha1 = "*"
url = "*"
utf-8 = "*"

[dependencies.native-tls]
optional = true
version = "*"
20 changes: 20 additions & 0 deletions LICENSE
@@ -0,0 +1,20 @@
Copyright (c) 2016 Alexey Galakhov
Copyright (c) 2016 Jason Housley

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
62 changes: 62 additions & 0 deletions examples/autobahn-client.rs
@@ -0,0 +1,62 @@
#[macro_use] extern crate log;
extern crate env_logger;
extern crate ws2;
extern crate url;

use url::Url;

use ws2::protocol::Message;
use ws2::client::connect;
use ws2::handshake::Handshake;
use ws2::error::{Error, Result};

const AGENT: &'static str = "WS2-RS";

fn get_case_count() -> Result<u32> {
let mut socket = connect(
Url::parse("ws://localhost:9001/getCaseCount").unwrap()
)?.handshake_wait()?;
let msg = socket.read_message()?;
socket.close();
Ok(msg.into_text()?.parse::<u32>().unwrap())
}

fn update_reports() -> Result<()> {
let mut socket = connect(
Url::parse(&format!("ws://localhost:9001/updateReports?agent={}", AGENT)).unwrap()
)?.handshake_wait()?;
socket.close();
Ok(())
}

fn run_test(case: u32) -> Result<()> {
info!("Running test case {}", case);
let case_url = Url::parse(
&format!("ws://localhost:9001/runCase?case={}&agent={}", case, AGENT)
).unwrap();
let mut socket = connect(case_url)?.handshake_wait()?;
loop {
let msg = socket.read_message()?;
socket.write_message(msg)?;
}
socket.close();
Ok(())
}

fn main() {
env_logger::init().unwrap();

let total = get_case_count().unwrap();

for case in 1..(total + 1) {
if let Err(e) = run_test(case) {
match e {
Error::Protocol(_) => { }
err => { warn!("test: {}", err); }
}
}
}

update_reports().unwrap();
}

25 changes: 25 additions & 0 deletions examples/client.rs
@@ -0,0 +1,25 @@
extern crate ws2;
extern crate url;
extern crate env_logger;

use url::Url;
use ws2::protocol::Message;
use ws2::client::connect;
use ws2::protocol::handshake::Handshake;

fn main() {
env_logger::init().unwrap();

let mut socket = connect(Url::parse("ws://localhost:3012/socket").unwrap())
.expect("Can't connect")
.handshake_wait()
.expect("Handshake error");

socket.write_message(Message::Text("Hello WebSocket".into()));
loop {
let msg = socket.read_message().expect("Error reading message");
println!("Received: {}", msg);
}
// socket.close();

}
75 changes: 75 additions & 0 deletions src/client.rs
@@ -0,0 +1,75 @@
use std::net::{TcpStream, ToSocketAddrs};
use url::{Url, SocketAddrs};

use protocol::WebSocket;
use handshake::{Handshake as HandshakeTrait, HandshakeResult};
use handshake::client::{ClientHandshake, Request};
use error::{Error, Result};

/// Connect to the given WebSocket.
///
/// Note that this function may block the current thread while DNS resolution is performed.
pub fn connect(url: Url) -> Result<Handshake> {
let mode = match url.scheme() {
"ws" => Mode::Plain,
#[cfg(feature="tls")]
"wss" => Mode::Tls,
_ => return Err(Error::Url("URL scheme not supported".into()))
};

// Note that this function may block the current thread while resolution is performed.
let addrs = url.to_socket_addrs()?;
Ok(Handshake {
state: HandshakeState::Nothing(url),
alt_addresses: addrs,
})
}

enum Mode {
Plain,
Tls,
}

enum HandshakeState {
Nothing(Url),
WebSocket(ClientHandshake<TcpStream>),
}

pub struct Handshake {
state: HandshakeState,
alt_addresses: SocketAddrs,
}

impl HandshakeTrait for Handshake {
type Stream = WebSocket<TcpStream>;
fn handshake(mut self) -> Result<HandshakeResult<Self>> {
match self.state {
HandshakeState::Nothing(url) => {
if let Some(addr) = self.alt_addresses.next() {
debug!("Trying to contact {} at {}...", url, addr);
let state = {
if let Ok(stream) = TcpStream::connect(addr) {
let hs = ClientHandshake::new(stream, Request { url: url });
HandshakeState::WebSocket(hs)
} else {
HandshakeState::Nothing(url)
}
};
Ok(HandshakeResult::Incomplete(Handshake {
state: state,
..self
}))
} else {
Err(Error::Url(format!("Unable to resolve {}", url).into()))
}
}
HandshakeState::WebSocket(ws) => {
let alt_addresses = self.alt_addresses;
ws.handshake().map(move |r| r.map(move |s| Handshake {
state: HandshakeState::WebSocket(s),
alt_addresses: alt_addresses,
}))
}
}
}
}
84 changes: 84 additions & 0 deletions src/error.rs
@@ -0,0 +1,84 @@
//! Error handling.

use std::borrow::{Borrow, Cow};

use std::error::Error as ErrorTrait;
use std::fmt;
use std::io;
use std::result;
use std::str;
use std::string;

use httparse;

pub type Result<T> = result::Result<T, Error>;

/// Possible WebSocket errors
#[derive(Debug)]
pub enum Error {
/// Input-output error
Io(io::Error),
/// Buffer capacity exhausted
Capacity(Cow<'static, str>),
/// Protocol violation
Protocol(Cow<'static, str>),
/// UTF coding error
Utf8(str::Utf8Error),
/// Invlid URL.
Url(Cow<'static, str>),
/// HTTP error.
Http(u16),
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Io(ref err) => write!(f, "IO error: {}", err),
Error::Capacity(ref msg) => write!(f, "Space limit exceeded: {}", msg),
Error::Protocol(ref msg) => write!(f, "WebSocket protocol error: {}", msg),
Error::Utf8(ref err) => write!(f, "UTF-8 encoding error: {}", err),
Error::Url(ref msg) => write!(f, "URL error: {}", msg),
Error::Http(code) => write!(f, "HTTP code: {}", code),
}
}
}

impl ErrorTrait for Error {
fn description(&self) -> &str {
match *self {
Error::Io(ref err) => err.description(),
Error::Capacity(ref msg) => msg.borrow(),
Error::Protocol(ref msg) => msg.borrow(),
Error::Utf8(ref err) => err.description(),
Error::Url(ref msg) => msg.borrow(),
Error::Http(_) => "",
}
}
}

impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::Io(err)
}
}

impl From<str::Utf8Error> for Error {
fn from(err: str::Utf8Error) -> Self {
Error::Utf8(err)
}
}

impl From<string::FromUtf8Error> for Error {
fn from(err: string::FromUtf8Error) -> Self {
Error::Utf8(err.utf8_error())
}
}

impl From<httparse::Error> for Error {
fn from(err: httparse::Error) -> Self {
match err {
httparse::Error::TooManyHeaders => Error::Capacity("Too many headers".into()),
e => Error::Protocol(Cow::Owned(e.description().into())),
}
}
}

0 comments on commit e63f594

Please sign in to comment.