Skip to content

Commit

Permalink
breaking: update tokio-tungstenite to 0.25 and update examples
Browse files Browse the repository at this point in the history
  • Loading branch information
adryzz committed Dec 15, 2024
1 parent c596dea commit 42bdf98
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 26 deletions.
2 changes: 1 addition & 1 deletion axum/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ serde_path_to_error = { version = "0.1.8", optional = true }
serde_urlencoded = { version = "0.7", optional = true }
sha1 = { version = "0.10", optional = true }
tokio = { package = "tokio", version = "1.25.0", features = ["time"], optional = true }
tokio-tungstenite = { version = "0.24.0", optional = true }
tokio-tungstenite = { version = "0.25.0", optional = true }
tracing = { version = "0.1", default-features = false, optional = true }

[dependencies.tower-http]
Expand Down
26 changes: 13 additions & 13 deletions axum/src/extract/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ use std::{
use tokio_tungstenite::{
tungstenite::{
self as ts,
protocol::{self, WebSocketConfig},
protocol::{self, frame::{Payload, Utf8Payload}, WebSocketConfig},
},
WebSocketStream,
};
Expand Down Expand Up @@ -591,24 +591,24 @@ pub struct CloseFrame<'t> {
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum Message {
/// A text WebSocket message
Text(String),
Text(Utf8Payload),
/// A binary WebSocket message
Binary(Vec<u8>),
Binary(Payload),
/// A ping message with the specified payload
///
/// The payload here must have a length less than 125 bytes.
///
/// Ping messages will be automatically responded to by the server, so you do not have to worry
/// about dealing with them yourself.
Ping(Vec<u8>),
Ping(Payload),
/// A pong message with the specified payload
///
/// The payload here must have a length less than 125 bytes.
///
/// Pong messages will be automatically sent to the client if a ping message is received, so
/// you do not have to worry about constructing them yourself unless you want to implement a
/// [unidirectional heartbeat](https://tools.ietf.org/html/rfc6455#section-5.5.3).
Pong(Vec<u8>),
Pong(Payload),
/// A close message with the optional close frame.
///
/// You may "uncleanly" close a WebSocket connection at any time
Expand Down Expand Up @@ -666,8 +666,8 @@ impl Message {
/// Consume the WebSocket and return it as binary data.
pub fn into_data(self) -> Vec<u8> {
match self {
Self::Text(string) => string.into_bytes(),
Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => data,
Self::Text(string) => string.to_string().into_bytes(),
Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => data.as_slice().to_vec(),
Self::Close(None) => Vec::new(),
Self::Close(Some(frame)) => frame.reason.into_owned().into_bytes(),
}
Expand All @@ -676,8 +676,8 @@ impl Message {
/// Attempt to consume the WebSocket message and convert it to a String.
pub fn into_text(self) -> Result<String, Error> {
match self {
Self::Text(string) => Ok(string),
Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => Ok(String::from_utf8(data)
Self::Text(string) => Ok(string.to_string()),
Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => Ok(String::from_utf8(data.as_slice().to_vec())
.map_err(|err| err.utf8_error())
.map_err(Error::new)?),
Self::Close(None) => Ok(String::new()),
Expand All @@ -689,9 +689,9 @@ impl Message {
/// this will try to convert binary data to utf8.
pub fn to_text(&self) -> Result<&str, Error> {
match *self {
Self::Text(ref string) => Ok(string),
Self::Text(ref string) => Ok(string.as_str()),
Self::Binary(ref data) | Self::Ping(ref data) | Self::Pong(ref data) => {
Ok(std::str::from_utf8(data).map_err(Error::new)?)
Ok(std::str::from_utf8(data.as_slice()).map_err(Error::new)?)
}
Self::Close(None) => Ok(""),
Self::Close(Some(ref frame)) => Ok(&frame.reason),
Expand All @@ -701,7 +701,7 @@ impl Message {

impl From<String> for Message {
fn from(string: String) -> Self {
Message::Text(string)
Message::Text(string.into())
}
}

Expand All @@ -719,7 +719,7 @@ impl<'b> From<&'b [u8]> for Message {

impl From<Vec<u8>> for Message {
fn from(data: Vec<u8>) -> Self {
Message::Binary(data)
Message::Binary(data.into())
}
}

Expand Down
6 changes: 3 additions & 3 deletions examples/chat/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,15 +79,15 @@ async fn websocket(stream: WebSocket, state: Arc<AppState>) {
while let Some(Ok(message)) = receiver.next().await {
if let Message::Text(name) = message {
// If username that is sent by client is not taken, fill username string.
check_username(&state, &mut username, &name);
check_username(&state, &mut username, name.as_str());

// If not empty we want to quit the loop else we want to quit function.
if !username.is_empty() {
break;
} else {
// Only send our client that username is taken.
let _ = sender
.send(Message::Text(String::from("Username already taken.")))
.send(Message::Text("Username already taken.".into()))
.await;

return;
Expand All @@ -109,7 +109,7 @@ async fn websocket(stream: WebSocket, state: Arc<AppState>) {
let mut send_task = tokio::spawn(async move {
while let Ok(msg) = rx.recv().await {
// In any websocket error, break loop.
if sender.send(Message::Text(msg)).await.is_err() {
if sender.send(Message::Text(msg.into())).await.is_err() {
break;
}
}
Expand Down
8 changes: 4 additions & 4 deletions examples/testing-websockets/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ async fn integration_testable_handle_socket(mut socket: WebSocket) {
while let Some(Ok(msg)) = socket.recv().await {
if let Message::Text(msg) = msg {
if socket
.send(Message::Text(format!("You said: {msg}")))
.send(Message::Text(format!("You said: {msg}").into()))
.await
.is_err()
{
Expand Down Expand Up @@ -79,7 +79,7 @@ where
while let Some(Ok(msg)) = read.next().await {
if let Message::Text(msg) = msg {
if write
.send(Message::Text(format!("You said: {msg}")))
.send(Message::Text(format!("You said: {msg}").into()))
.await
.is_err()
{
Expand Down Expand Up @@ -137,7 +137,7 @@ mod tests {
tokio::spawn(unit_testable_handle_socket(socket_write, socket_read));

test_tx
.send(Ok(Message::Text("foo".to_owned())))
.send(Ok(Message::Text("foo".into())))
.await
.unwrap();

Expand All @@ -146,6 +146,6 @@ mod tests {
other => panic!("expected a text message but got {other:?}"),
};

assert_eq!(msg, "You said: foo");
assert_eq!(msg.as_str(), "You said: foo");
}
}
4 changes: 2 additions & 2 deletions examples/websockets-http2/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ async fn ws_handler(
res = ws.recv() => {
match res {
Some(Ok(ws::Message::Text(s))) => {
let _ = sender.send(s);
let _ = sender.send(s.to_string());
}
Some(Ok(_)) => {}
Some(Err(e)) => tracing::debug!("client disconnected abruptly: {e}"),
Expand All @@ -85,7 +85,7 @@ async fn ws_handler(
// Tokio guarantees that `broadcast::Receiver::recv` is cancel-safe.
res = receiver.recv() => {
match res {
Ok(msg) => if let Err(e) = ws.send(ws::Message::Text(msg)).await {
Ok(msg) => if let Err(e) = ws.send(ws::Message::Text(msg.into())).await {
tracing::debug!("client disconnected abruptly: {e}");
}
Err(_) => continue,
Expand Down
6 changes: 3 additions & 3 deletions examples/websockets/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ async fn ws_handler(
/// Actual websocket statemachine (one will be spawned per connection)
async fn handle_socket(mut socket: WebSocket, who: SocketAddr) {
// send a ping (unsupported by some browsers) just to kick things off and get a response
if socket.send(Message::Ping(vec![1, 2, 3])).await.is_ok() {
if socket.send(Message::Ping(vec![1, 2, 3].into())).await.is_ok() {
println!("Pinged {who}...");
} else {
println!("Could not send ping {who}!");
Expand Down Expand Up @@ -131,7 +131,7 @@ async fn handle_socket(mut socket: WebSocket, who: SocketAddr) {
// connecting to server and receiving their greetings.
for i in 1..5 {
if socket
.send(Message::Text(format!("Hi {i} times!")))
.send(Message::Text(format!("Hi {i} times!").into()))
.await
.is_err()
{
Expand All @@ -151,7 +151,7 @@ async fn handle_socket(mut socket: WebSocket, who: SocketAddr) {
for i in 0..n_msg {
// In case of any websocket error, we exit.
if sender
.send(Message::Text(format!("Server message {i} ...")))
.send(Message::Text(format!("Server message {i} ...").into()))
.await
.is_err()
{
Expand Down

0 comments on commit 42bdf98

Please sign in to comment.