mirror of
https://github.com/actix/actix-web.git
synced 2025-01-02 05:18:44 +00:00
use ByteString as container for websocket text message (#1864)
This commit is contained in:
parent
36aee18c64
commit
7d632d0b7b
13 changed files with 131 additions and 102 deletions
|
@ -2,14 +2,11 @@
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
### Changed
|
### Changed
|
||||||
* Bumped `rand` to `0.8`.
|
|
||||||
* Update `actix-*` dependencies to tokio `1.0` based versions. [#1813]
|
* Update `actix-*` dependencies to tokio `1.0` based versions. [#1813]
|
||||||
|
* Bumped `rand` to `0.8`.
|
||||||
* Update `bytes` to `1.0`. [#1813]
|
* Update `bytes` to `1.0`. [#1813]
|
||||||
* Update `h2` to `0.3`. [#1813]
|
* Update `h2` to `0.3`. [#1813]
|
||||||
|
* The `ws::Message::Text` enum variant now contains a `bytestring::ByteString`. [#1864]
|
||||||
|
|
||||||
[#1813]: https://github.com/actix/actix-web/pull/1813
|
|
||||||
|
|
||||||
|
|
||||||
### Removed
|
### Removed
|
||||||
* Deprecated `on_connect` methods have been removed. Prefer the new
|
* Deprecated `on_connect` methods have been removed. Prefer the new
|
||||||
|
@ -22,6 +19,7 @@
|
||||||
|
|
||||||
[#1813]: https://github.com/actix/actix-web/pull/1813
|
[#1813]: https://github.com/actix/actix-web/pull/1813
|
||||||
[#1857]: https://github.com/actix/actix-web/pull/1857
|
[#1857]: https://github.com/actix/actix-web/pull/1857
|
||||||
|
[#1864]: https://github.com/actix/actix-web/pull/1864
|
||||||
|
|
||||||
|
|
||||||
## 2.2.0 - 2020-11-25
|
## 2.2.0 - 2020-11-25
|
||||||
|
|
|
@ -51,9 +51,10 @@ actix = { version = "0.11.0-beta.1", optional = true }
|
||||||
base64 = "0.13"
|
base64 = "0.13"
|
||||||
bitflags = "1.2"
|
bitflags = "1.2"
|
||||||
bytes = "1"
|
bytes = "1"
|
||||||
|
bytestring = "1"
|
||||||
cookie = { version = "0.14.1", features = ["percent-encode"] }
|
cookie = { version = "0.14.1", features = ["percent-encode"] }
|
||||||
copyless = "0.1.4"
|
copyless = "0.1.4"
|
||||||
derive_more = "0.99.2"
|
derive_more = "0.99.5"
|
||||||
either = "1.5.3"
|
either = "1.5.3"
|
||||||
encoding_rs = "0.8"
|
encoding_rs = "0.8"
|
||||||
futures-channel = { version = "0.3.7", default-features = false }
|
futures-channel = { version = "0.3.7", default-features = false }
|
||||||
|
|
|
@ -1,47 +1,60 @@
|
||||||
use actix_codec::{Decoder, Encoder};
|
use actix_codec::{Decoder, Encoder};
|
||||||
|
use bitflags::bitflags;
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
|
use bytestring::ByteString;
|
||||||
|
|
||||||
use super::frame::Parser;
|
use super::frame::Parser;
|
||||||
use super::proto::{CloseReason, OpCode};
|
use super::proto::{CloseReason, OpCode};
|
||||||
use super::ProtocolError;
|
use super::ProtocolError;
|
||||||
|
|
||||||
/// `WebSocket` Message
|
/// A WebSocket message.
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq)]
|
||||||
pub enum Message {
|
pub enum Message {
|
||||||
/// Text message
|
/// Text message.
|
||||||
Text(String),
|
Text(ByteString),
|
||||||
/// Binary message
|
|
||||||
|
/// Binary message.
|
||||||
Binary(Bytes),
|
Binary(Bytes),
|
||||||
/// Continuation
|
|
||||||
|
/// Continuation.
|
||||||
Continuation(Item),
|
Continuation(Item),
|
||||||
/// Ping message
|
|
||||||
|
/// Ping message.
|
||||||
Ping(Bytes),
|
Ping(Bytes),
|
||||||
/// Pong message
|
|
||||||
|
/// Pong message.
|
||||||
Pong(Bytes),
|
Pong(Bytes),
|
||||||
/// Close message with optional reason
|
|
||||||
|
/// Close message with optional reason.
|
||||||
Close(Option<CloseReason>),
|
Close(Option<CloseReason>),
|
||||||
/// No-op. Useful for actix-net services
|
|
||||||
|
/// No-op. Useful for low-level services.
|
||||||
Nop,
|
Nop,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `WebSocket` frame
|
/// A WebSocket frame.
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq)]
|
||||||
pub enum Frame {
|
pub enum Frame {
|
||||||
/// Text frame, codec does not verify utf8 encoding
|
/// Text frame. Note that the codec does not validate UTF-8 encoding.
|
||||||
Text(Bytes),
|
Text(Bytes),
|
||||||
/// Binary frame
|
|
||||||
|
/// Binary frame.
|
||||||
Binary(Bytes),
|
Binary(Bytes),
|
||||||
/// Continuation
|
|
||||||
|
/// Continuation.
|
||||||
Continuation(Item),
|
Continuation(Item),
|
||||||
/// Ping message
|
|
||||||
|
/// Ping message.
|
||||||
Ping(Bytes),
|
Ping(Bytes),
|
||||||
/// Pong message
|
|
||||||
|
/// Pong message.
|
||||||
Pong(Bytes),
|
Pong(Bytes),
|
||||||
/// Close message with optional reason
|
|
||||||
|
/// Close message with optional reason.
|
||||||
Close(Option<CloseReason>),
|
Close(Option<CloseReason>),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `WebSocket` continuation item
|
/// A `WebSocket` continuation item.
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq)]
|
||||||
pub enum Item {
|
pub enum Item {
|
||||||
FirstText(Bytes),
|
FirstText(Bytes),
|
||||||
|
@ -51,13 +64,13 @@ pub enum Item {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone)]
|
#[derive(Debug, Copy, Clone)]
|
||||||
/// WebSockets protocol codec
|
/// WebSocket protocol codec.
|
||||||
pub struct Codec {
|
pub struct Codec {
|
||||||
flags: Flags,
|
flags: Flags,
|
||||||
max_size: usize,
|
max_size: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
bitflags::bitflags! {
|
bitflags! {
|
||||||
struct Flags: u8 {
|
struct Flags: u8 {
|
||||||
const SERVER = 0b0000_0001;
|
const SERVER = 0b0000_0001;
|
||||||
const CONTINUATION = 0b0000_0010;
|
const CONTINUATION = 0b0000_0010;
|
||||||
|
@ -66,7 +79,7 @@ bitflags::bitflags! {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Codec {
|
impl Codec {
|
||||||
/// Create new websocket frames decoder
|
/// Create new websocket frames decoder.
|
||||||
pub fn new() -> Codec {
|
pub fn new() -> Codec {
|
||||||
Codec {
|
Codec {
|
||||||
max_size: 65_536,
|
max_size: 65_536,
|
||||||
|
@ -74,9 +87,9 @@ impl Codec {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set max frame size
|
/// Set max frame size.
|
||||||
///
|
///
|
||||||
/// By default max size is set to 64kb
|
/// By default max size is set to 64kb.
|
||||||
pub fn max_size(mut self, size: usize) -> Self {
|
pub fn max_size(mut self, size: usize) -> Self {
|
||||||
self.max_size = size;
|
self.max_size = size;
|
||||||
self
|
self
|
||||||
|
|
|
@ -1,11 +1,11 @@
|
||||||
//! WebSocket protocol support.
|
//! WebSocket protocol support.
|
||||||
//!
|
//!
|
||||||
//! To setup a `WebSocket`, first do web socket handshake then on success
|
//! To setup a WebSocket, first do web socket handshake then on success convert `Payload` into a
|
||||||
//! convert `Payload` into a `WsStream` stream and then use `WsWriter` to
|
//! `WsStream` stream and then use `WsWriter` to communicate with the peer.
|
||||||
//! communicate with the peer.
|
|
||||||
use std::io;
|
use std::io;
|
||||||
|
|
||||||
use derive_more::{Display, From};
|
use derive_more::{Display, Error, From};
|
||||||
use http::{header, Method, StatusCode};
|
use http::{header, Method, StatusCode};
|
||||||
|
|
||||||
use crate::error::ResponseError;
|
use crate::error::ResponseError;
|
||||||
|
@ -23,86 +23,103 @@ pub use self::dispatcher::Dispatcher;
|
||||||
pub use self::frame::Parser;
|
pub use self::frame::Parser;
|
||||||
pub use self::proto::{hash_key, CloseCode, CloseReason, OpCode};
|
pub use self::proto::{hash_key, CloseCode, CloseReason, OpCode};
|
||||||
|
|
||||||
/// Websocket protocol errors
|
/// WebSocket protocol errors.
|
||||||
#[derive(Debug, Display, From)]
|
#[derive(Debug, Display, From, Error)]
|
||||||
pub enum ProtocolError {
|
pub enum ProtocolError {
|
||||||
/// Received an unmasked frame from client
|
/// Received an unmasked frame from client.
|
||||||
#[display(fmt = "Received an unmasked frame from client")]
|
#[display(fmt = "Received an unmasked frame from client.")]
|
||||||
UnmaskedFrame,
|
UnmaskedFrame,
|
||||||
/// Received a masked frame from server
|
|
||||||
#[display(fmt = "Received a masked frame from server")]
|
/// Received a masked frame from server.
|
||||||
|
#[display(fmt = "Received a masked frame from server.")]
|
||||||
MaskedFrame,
|
MaskedFrame,
|
||||||
/// Encountered invalid opcode
|
|
||||||
#[display(fmt = "Invalid opcode: {}", _0)]
|
/// Encountered invalid opcode.
|
||||||
InvalidOpcode(u8),
|
#[display(fmt = "Invalid opcode: {}.", _0)]
|
||||||
|
InvalidOpcode(#[error(not(source))] u8),
|
||||||
|
|
||||||
/// Invalid control frame length
|
/// Invalid control frame length
|
||||||
#[display(fmt = "Invalid control frame length: {}", _0)]
|
#[display(fmt = "Invalid control frame length: {}.", _0)]
|
||||||
InvalidLength(usize),
|
InvalidLength(#[error(not(source))] usize),
|
||||||
/// Bad web socket op code
|
|
||||||
#[display(fmt = "Bad web socket op code")]
|
/// Bad opcode.
|
||||||
|
#[display(fmt = "Bad opcode.")]
|
||||||
BadOpCode,
|
BadOpCode,
|
||||||
|
|
||||||
/// A payload reached size limit.
|
/// A payload reached size limit.
|
||||||
#[display(fmt = "A payload reached size limit.")]
|
#[display(fmt = "A payload reached size limit.")]
|
||||||
Overflow,
|
Overflow,
|
||||||
/// Continuation is not started
|
|
||||||
|
/// Continuation is not started.
|
||||||
#[display(fmt = "Continuation is not started.")]
|
#[display(fmt = "Continuation is not started.")]
|
||||||
ContinuationNotStarted,
|
ContinuationNotStarted,
|
||||||
/// Received new continuation but it is already started
|
|
||||||
#[display(fmt = "Received new continuation but it is already started")]
|
/// Received new continuation but it is already started.
|
||||||
|
#[display(fmt = "Received new continuation but it is already started.")]
|
||||||
ContinuationStarted,
|
ContinuationStarted,
|
||||||
/// Unknown continuation fragment
|
|
||||||
#[display(fmt = "Unknown continuation fragment.")]
|
/// Unknown continuation fragment.
|
||||||
ContinuationFragment(OpCode),
|
#[display(fmt = "Unknown continuation fragment: {}.", _0)]
|
||||||
/// Io error
|
ContinuationFragment(#[error(not(source))] OpCode),
|
||||||
#[display(fmt = "io error: {}", _0)]
|
|
||||||
|
/// I/O error.
|
||||||
|
#[display(fmt = "I/O error: {}", _0)]
|
||||||
Io(io::Error),
|
Io(io::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::error::Error for ProtocolError {}
|
|
||||||
|
|
||||||
impl ResponseError for ProtocolError {}
|
impl ResponseError for ProtocolError {}
|
||||||
|
|
||||||
/// Websocket handshake errors
|
/// WebSocket handshake errors
|
||||||
#[derive(PartialEq, Debug, Display)]
|
#[derive(PartialEq, Debug, Display)]
|
||||||
pub enum HandshakeError {
|
pub enum HandshakeError {
|
||||||
/// Only get method is allowed
|
/// Only get method is allowed.
|
||||||
#[display(fmt = "Method not allowed")]
|
#[display(fmt = "Method not allowed.")]
|
||||||
GetMethodRequired,
|
GetMethodRequired,
|
||||||
/// Upgrade header if not set to websocket
|
|
||||||
#[display(fmt = "Websocket upgrade is expected")]
|
/// Upgrade header if not set to websocket.
|
||||||
|
#[display(fmt = "WebSocket upgrade is expected.")]
|
||||||
NoWebsocketUpgrade,
|
NoWebsocketUpgrade,
|
||||||
/// Connection header is not set to upgrade
|
|
||||||
#[display(fmt = "Connection upgrade is expected")]
|
/// Connection header is not set to upgrade.
|
||||||
|
#[display(fmt = "Connection upgrade is expected.")]
|
||||||
NoConnectionUpgrade,
|
NoConnectionUpgrade,
|
||||||
/// Websocket version header is not set
|
|
||||||
#[display(fmt = "Websocket version header is required")]
|
/// WebSocket version header is not set.
|
||||||
|
#[display(fmt = "WebSocket version header is required.")]
|
||||||
NoVersionHeader,
|
NoVersionHeader,
|
||||||
/// Unsupported websocket version
|
|
||||||
#[display(fmt = "Unsupported version")]
|
/// Unsupported websocket version.
|
||||||
|
#[display(fmt = "Unsupported version.")]
|
||||||
UnsupportedVersion,
|
UnsupportedVersion,
|
||||||
/// Websocket key is not set or wrong
|
|
||||||
#[display(fmt = "Unknown websocket key")]
|
/// WebSocket key is not set or wrong.
|
||||||
|
#[display(fmt = "Unknown websocket key.")]
|
||||||
BadWebsocketKey,
|
BadWebsocketKey,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ResponseError for HandshakeError {
|
impl ResponseError for HandshakeError {
|
||||||
fn error_response(&self) -> Response {
|
fn error_response(&self) -> Response {
|
||||||
match *self {
|
match self {
|
||||||
HandshakeError::GetMethodRequired => Response::MethodNotAllowed()
|
HandshakeError::GetMethodRequired => Response::MethodNotAllowed()
|
||||||
.header(header::ALLOW, "GET")
|
.header(header::ALLOW, "GET")
|
||||||
.finish(),
|
.finish(),
|
||||||
|
|
||||||
HandshakeError::NoWebsocketUpgrade => Response::BadRequest()
|
HandshakeError::NoWebsocketUpgrade => Response::BadRequest()
|
||||||
.reason("No WebSocket UPGRADE header found")
|
.reason("No WebSocket UPGRADE header found")
|
||||||
.finish(),
|
.finish(),
|
||||||
|
|
||||||
HandshakeError::NoConnectionUpgrade => Response::BadRequest()
|
HandshakeError::NoConnectionUpgrade => Response::BadRequest()
|
||||||
.reason("No CONNECTION upgrade")
|
.reason("No CONNECTION upgrade")
|
||||||
.finish(),
|
.finish(),
|
||||||
|
|
||||||
HandshakeError::NoVersionHeader => Response::BadRequest()
|
HandshakeError::NoVersionHeader => Response::BadRequest()
|
||||||
.reason("Websocket version header is required")
|
.reason("Websocket version header is required")
|
||||||
.finish(),
|
.finish(),
|
||||||
|
|
||||||
HandshakeError::UnsupportedVersion => Response::BadRequest()
|
HandshakeError::UnsupportedVersion => Response::BadRequest()
|
||||||
.reason("Unsupported version")
|
.reason("Unsupported version")
|
||||||
.finish(),
|
.finish(),
|
||||||
|
|
||||||
HandshakeError::BadWebsocketKey => {
|
HandshakeError::BadWebsocketKey => {
|
||||||
Response::BadRequest().reason("Handshake error").finish()
|
Response::BadRequest().reason("Handshake error").finish()
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,21 +2,27 @@ use std::convert::{From, Into};
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
use self::OpCode::*;
|
use self::OpCode::*;
|
||||||
/// Operation codes as part of rfc6455.
|
/// Operation codes as part of RFC6455.
|
||||||
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
|
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
|
||||||
pub enum OpCode {
|
pub enum OpCode {
|
||||||
/// Indicates a continuation frame of a fragmented message.
|
/// Indicates a continuation frame of a fragmented message.
|
||||||
Continue,
|
Continue,
|
||||||
|
|
||||||
/// Indicates a text data frame.
|
/// Indicates a text data frame.
|
||||||
Text,
|
Text,
|
||||||
|
|
||||||
/// Indicates a binary data frame.
|
/// Indicates a binary data frame.
|
||||||
Binary,
|
Binary,
|
||||||
|
|
||||||
/// Indicates a close control frame.
|
/// Indicates a close control frame.
|
||||||
Close,
|
Close,
|
||||||
|
|
||||||
/// Indicates a ping control frame.
|
/// Indicates a ping control frame.
|
||||||
Ping,
|
Ping,
|
||||||
|
|
||||||
/// Indicates a pong control frame.
|
/// Indicates a pong control frame.
|
||||||
Pong,
|
Pong,
|
||||||
|
|
||||||
/// Indicates an invalid opcode was received.
|
/// Indicates an invalid opcode was received.
|
||||||
Bad,
|
Bad,
|
||||||
}
|
}
|
||||||
|
|
|
@ -74,7 +74,7 @@ async fn service(msg: ws::Frame) -> Result<ws::Message, Error> {
|
||||||
let msg = match msg {
|
let msg = match msg {
|
||||||
ws::Frame::Ping(msg) => ws::Message::Pong(msg),
|
ws::Frame::Ping(msg) => ws::Message::Pong(msg),
|
||||||
ws::Frame::Text(text) => {
|
ws::Frame::Text(text) => {
|
||||||
ws::Message::Text(String::from_utf8_lossy(&text).to_string())
|
ws::Message::Text(String::from_utf8_lossy(&text).into_owned().into())
|
||||||
}
|
}
|
||||||
ws::Frame::Binary(bin) => ws::Message::Binary(bin),
|
ws::Frame::Binary(bin) => ws::Message::Binary(bin),
|
||||||
ws::Frame::Continuation(item) => ws::Message::Continuation(item),
|
ws::Frame::Continuation(item) => ws::Message::Continuation(item),
|
||||||
|
@ -101,10 +101,7 @@ async fn test_simple() {
|
||||||
|
|
||||||
// client service
|
// client service
|
||||||
let mut framed = srv.ws().await.unwrap();
|
let mut framed = srv.ws().await.unwrap();
|
||||||
framed
|
framed.send(ws::Message::Text("text".into())).await.unwrap();
|
||||||
.send(ws::Message::Text("text".to_string()))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let (item, mut framed) = framed.into_future().await;
|
let (item, mut framed) = framed.into_future().await;
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
item.unwrap().unwrap(),
|
item.unwrap().unwrap(),
|
||||||
|
|
|
@ -3,8 +3,10 @@
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased - 2021-xx-xx
|
||||||
* Update `pin-project` to `1.0`.
|
* Update `pin-project` to `1.0`.
|
||||||
* Update `bytes` to `1.0`. [#1813]
|
* Update `bytes` to `1.0`. [#1813]
|
||||||
|
* `WebsocketContext::text` now takes an `Into<bytestring::ByteString>`. [#1864]
|
||||||
|
|
||||||
[#1813]: https://github.com/actix/actix-web/pull/1813
|
[#1813]: https://github.com/actix/actix-web/pull/1813
|
||||||
|
[#1864]: https://github.com/actix/actix-web/pull/1864
|
||||||
|
|
||||||
## 3.0.0 - 2020-09-11
|
## 3.0.0 - 2020-09-11
|
||||||
* No significant changes from `3.0.0-beta.2`.
|
* No significant changes from `3.0.0-beta.2`.
|
||||||
|
|
|
@ -22,6 +22,7 @@ actix-http = "2.0.0"
|
||||||
actix-web = { version = "3.0.0", default-features = false }
|
actix-web = { version = "3.0.0", default-features = false }
|
||||||
|
|
||||||
bytes = "1"
|
bytes = "1"
|
||||||
|
bytestring = "1"
|
||||||
futures-core = { version = "0.3.7", default-features = false }
|
futures-core = { version = "0.3.7", default-features = false }
|
||||||
pin-project = "1.0.0"
|
pin-project = "1.0.0"
|
||||||
tokio = { version = "1", features = ["sync"] }
|
tokio = { version = "1", features = ["sync"] }
|
||||||
|
|
|
@ -1,9 +1,10 @@
|
||||||
//! Websocket integration
|
//! Websocket integration.
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
use std::{collections::VecDeque, convert::TryFrom};
|
||||||
|
|
||||||
use actix::dev::{
|
use actix::dev::{
|
||||||
AsyncContextParts, ContextFut, ContextParts, Envelope, Mailbox, StreamHandler,
|
AsyncContextParts, ContextFut, ContextParts, Envelope, Mailbox, StreamHandler,
|
||||||
|
@ -24,10 +25,11 @@ use actix_web::error::{Error, PayloadError};
|
||||||
use actix_web::http::{header, Method, StatusCode};
|
use actix_web::http::{header, Method, StatusCode};
|
||||||
use actix_web::{HttpRequest, HttpResponse};
|
use actix_web::{HttpRequest, HttpResponse};
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
|
use bytestring::ByteString;
|
||||||
use futures_core::Stream;
|
use futures_core::Stream;
|
||||||
use tokio::sync::oneshot::Sender;
|
use tokio::sync::oneshot::Sender;
|
||||||
|
|
||||||
/// Do websocket handshake and start ws actor.
|
/// Perform WebSocket handshake and start actor.
|
||||||
pub fn start<A, T>(actor: A, req: &HttpRequest, stream: T) -> Result<HttpResponse, Error>
|
pub fn start<A, T>(actor: A, req: &HttpRequest, stream: T) -> Result<HttpResponse, Error>
|
||||||
where
|
where
|
||||||
A: Actor<Context = WebsocketContext<A>>
|
A: Actor<Context = WebsocketContext<A>>
|
||||||
|
@ -38,7 +40,7 @@ where
|
||||||
Ok(res.streaming(WebsocketContext::create(actor, stream)))
|
Ok(res.streaming(WebsocketContext::create(actor, stream)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Do websocket handshake and start ws actor.
|
/// Perform WebSocket handshake and start actor.
|
||||||
///
|
///
|
||||||
/// `req` is an HTTP Request that should be requesting a websocket protocol
|
/// `req` is an HTTP Request that should be requesting a websocket protocol
|
||||||
/// change. `stream` should be a `Bytes` stream (such as
|
/// change. `stream` should be a `Bytes` stream (such as
|
||||||
|
@ -338,13 +340,13 @@ where
|
||||||
|
|
||||||
/// Send text frame
|
/// Send text frame
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn text<T: Into<String>>(&mut self, text: T) {
|
pub fn text(&mut self, text: impl Into<ByteString>) {
|
||||||
self.write_raw(Message::Text(text.into()));
|
self.write_raw(Message::Text(text.into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send binary frame
|
/// Send binary frame
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn binary<B: Into<Bytes>>(&mut self, data: B) {
|
pub fn binary(&mut self, data: impl Into<Bytes>) {
|
||||||
self.write_raw(Message::Binary(data.into()));
|
self.write_raw(Message::Binary(data.into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -528,16 +530,14 @@ where
|
||||||
}
|
}
|
||||||
Some(frm) => {
|
Some(frm) => {
|
||||||
let msg = match frm {
|
let msg = match frm {
|
||||||
Frame::Text(data) => Message::Text(
|
Frame::Text(data) => {
|
||||||
std::str::from_utf8(&data)
|
Message::Text(ByteString::try_from(data).map_err(|e| {
|
||||||
.map_err(|e| {
|
ProtocolError::Io(io::Error::new(
|
||||||
ProtocolError::Io(io::Error::new(
|
io::ErrorKind::Other,
|
||||||
io::ErrorKind::Other,
|
format!("{}", e),
|
||||||
format!("{}", e),
|
))
|
||||||
))
|
})?)
|
||||||
})?
|
}
|
||||||
.to_string(),
|
|
||||||
),
|
|
||||||
Frame::Binary(data) => Message::Binary(data),
|
Frame::Binary(data) => Message::Binary(data),
|
||||||
Frame::Ping(s) => Message::Ping(s),
|
Frame::Ping(s) => Message::Ping(s),
|
||||||
Frame::Pong(s) => Message::Pong(s),
|
Frame::Pong(s) => Message::Pong(s),
|
||||||
|
|
|
@ -38,10 +38,7 @@ async fn test_simple() {
|
||||||
|
|
||||||
// client service
|
// client service
|
||||||
let mut framed = srv.ws().await.unwrap();
|
let mut framed = srv.ws().await.unwrap();
|
||||||
framed
|
framed.send(ws::Message::Text("text".into())).await.unwrap();
|
||||||
.send(ws::Message::Text("text".to_string()))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let item = framed.next().await.unwrap().unwrap();
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
assert_eq!(item, ws::Frame::Text(Bytes::from_static(b"text")));
|
assert_eq!(item, ws::Frame::Text(Bytes::from_static(b"text")));
|
||||||
|
|
|
@ -76,7 +76,7 @@
|
||||||
//! .await?;
|
//! .await?;
|
||||||
//!
|
//!
|
||||||
//! connection
|
//! connection
|
||||||
//! .send(awc::ws::Message::Text("Echo".to_string()))
|
//! .send(awc::ws::Message::Text("Echo".into()))
|
||||||
//! .await?;
|
//! .await?;
|
||||||
//! let response = connection.next().await.unwrap()?;
|
//! let response = connection.next().await.unwrap()?;
|
||||||
//! # assert_eq!(response, awc::ws::Frame::Text("Echo".as_bytes().into()));
|
//! # assert_eq!(response, awc::ws::Frame::Text("Echo".as_bytes().into()));
|
||||||
|
|
|
@ -17,7 +17,7 @@
|
||||||
//! .unwrap();
|
//! .unwrap();
|
||||||
//!
|
//!
|
||||||
//! connection
|
//! connection
|
||||||
//! .send(ws::Message::Text("Echo".to_string()))
|
//! .send(ws::Message::Text("Echo".into()))
|
||||||
//! .await
|
//! .await
|
||||||
//! .unwrap();
|
//! .unwrap();
|
||||||
//! let response = connection.next().await.unwrap().unwrap();
|
//! let response = connection.next().await.unwrap().unwrap();
|
||||||
|
|
|
@ -11,7 +11,7 @@ async fn ws_service(req: ws::Frame) -> Result<ws::Message, io::Error> {
|
||||||
match req {
|
match req {
|
||||||
ws::Frame::Ping(msg) => Ok(ws::Message::Pong(msg)),
|
ws::Frame::Ping(msg) => Ok(ws::Message::Pong(msg)),
|
||||||
ws::Frame::Text(text) => Ok(ws::Message::Text(
|
ws::Frame::Text(text) => Ok(ws::Message::Text(
|
||||||
String::from_utf8(Vec::from(text.as_ref())).unwrap(),
|
String::from_utf8(Vec::from(text.as_ref())).unwrap().into(),
|
||||||
)),
|
)),
|
||||||
ws::Frame::Binary(bin) => Ok(ws::Message::Binary(bin)),
|
ws::Frame::Binary(bin) => Ok(ws::Message::Binary(bin)),
|
||||||
ws::Frame::Close(reason) => Ok(ws::Message::Close(reason)),
|
ws::Frame::Close(reason) => Ok(ws::Message::Close(reason)),
|
||||||
|
@ -43,10 +43,7 @@ async fn test_simple() {
|
||||||
|
|
||||||
// client service
|
// client service
|
||||||
let mut framed = srv.ws().await.unwrap();
|
let mut framed = srv.ws().await.unwrap();
|
||||||
framed
|
framed.send(ws::Message::Text("text".into())).await.unwrap();
|
||||||
.send(ws::Message::Text("text".to_string()))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let item = framed.next().await.unwrap().unwrap();
|
let item = framed.next().await.unwrap().unwrap();
|
||||||
assert_eq!(item, ws::Frame::Text(Bytes::from_static(b"text")));
|
assert_eq!(item, ws::Frame::Text(Bytes::from_static(b"text")));
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue