Skip to content

Commit 42bdf98

Browse files
committed
breaking: update tokio-tungstenite to 0.25 and update examples
1 parent c596dea commit 42bdf98

File tree

6 files changed

+26
-26
lines changed

6 files changed

+26
-26
lines changed

axum/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ serde_path_to_error = { version = "0.1.8", optional = true }
7676
serde_urlencoded = { version = "0.7", optional = true }
7777
sha1 = { version = "0.10", optional = true }
7878
tokio = { package = "tokio", version = "1.25.0", features = ["time"], optional = true }
79-
tokio-tungstenite = { version = "0.24.0", optional = true }
79+
tokio-tungstenite = { version = "0.25.0", optional = true }
8080
tracing = { version = "0.1", default-features = false, optional = true }
8181

8282
[dependencies.tower-http]

axum/src/extract/ws.rs

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ use std::{
114114
use tokio_tungstenite::{
115115
tungstenite::{
116116
self as ts,
117-
protocol::{self, WebSocketConfig},
117+
protocol::{self, frame::{Payload, Utf8Payload}, WebSocketConfig},
118118
},
119119
WebSocketStream,
120120
};
@@ -591,24 +591,24 @@ pub struct CloseFrame<'t> {
591591
#[derive(Debug, Eq, PartialEq, Clone)]
592592
pub enum Message {
593593
/// A text WebSocket message
594-
Text(String),
594+
Text(Utf8Payload),
595595
/// A binary WebSocket message
596-
Binary(Vec<u8>),
596+
Binary(Payload),
597597
/// A ping message with the specified payload
598598
///
599599
/// The payload here must have a length less than 125 bytes.
600600
///
601601
/// Ping messages will be automatically responded to by the server, so you do not have to worry
602602
/// about dealing with them yourself.
603-
Ping(Vec<u8>),
603+
Ping(Payload),
604604
/// A pong message with the specified payload
605605
///
606606
/// The payload here must have a length less than 125 bytes.
607607
///
608608
/// Pong messages will be automatically sent to the client if a ping message is received, so
609609
/// you do not have to worry about constructing them yourself unless you want to implement a
610610
/// [unidirectional heartbeat](https://tools.ietf.org/html/rfc6455#section-5.5.3).
611-
Pong(Vec<u8>),
611+
Pong(Payload),
612612
/// A close message with the optional close frame.
613613
///
614614
/// You may "uncleanly" close a WebSocket connection at any time
@@ -666,8 +666,8 @@ impl Message {
666666
/// Consume the WebSocket and return it as binary data.
667667
pub fn into_data(self) -> Vec<u8> {
668668
match self {
669-
Self::Text(string) => string.into_bytes(),
670-
Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => data,
669+
Self::Text(string) => string.to_string().into_bytes(),
670+
Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => data.as_slice().to_vec(),
671671
Self::Close(None) => Vec::new(),
672672
Self::Close(Some(frame)) => frame.reason.into_owned().into_bytes(),
673673
}
@@ -676,8 +676,8 @@ impl Message {
676676
/// Attempt to consume the WebSocket message and convert it to a String.
677677
pub fn into_text(self) -> Result<String, Error> {
678678
match self {
679-
Self::Text(string) => Ok(string),
680-
Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => Ok(String::from_utf8(data)
679+
Self::Text(string) => Ok(string.to_string()),
680+
Self::Binary(data) | Self::Ping(data) | Self::Pong(data) => Ok(String::from_utf8(data.as_slice().to_vec())
681681
.map_err(|err| err.utf8_error())
682682
.map_err(Error::new)?),
683683
Self::Close(None) => Ok(String::new()),
@@ -689,9 +689,9 @@ impl Message {
689689
/// this will try to convert binary data to utf8.
690690
pub fn to_text(&self) -> Result<&str, Error> {
691691
match *self {
692-
Self::Text(ref string) => Ok(string),
692+
Self::Text(ref string) => Ok(string.as_str()),
693693
Self::Binary(ref data) | Self::Ping(ref data) | Self::Pong(ref data) => {
694-
Ok(std::str::from_utf8(data).map_err(Error::new)?)
694+
Ok(std::str::from_utf8(data.as_slice()).map_err(Error::new)?)
695695
}
696696
Self::Close(None) => Ok(""),
697697
Self::Close(Some(ref frame)) => Ok(&frame.reason),
@@ -701,7 +701,7 @@ impl Message {
701701

702702
impl From<String> for Message {
703703
fn from(string: String) -> Self {
704-
Message::Text(string)
704+
Message::Text(string.into())
705705
}
706706
}
707707

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

720720
impl From<Vec<u8>> for Message {
721721
fn from(data: Vec<u8>) -> Self {
722-
Message::Binary(data)
722+
Message::Binary(data.into())
723723
}
724724
}
725725

examples/chat/src/main.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,15 +79,15 @@ async fn websocket(stream: WebSocket, state: Arc<AppState>) {
7979
while let Some(Ok(message)) = receiver.next().await {
8080
if let Message::Text(name) = message {
8181
// If username that is sent by client is not taken, fill username string.
82-
check_username(&state, &mut username, &name);
82+
check_username(&state, &mut username, name.as_str());
8383

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

9393
return;
@@ -109,7 +109,7 @@ async fn websocket(stream: WebSocket, state: Arc<AppState>) {
109109
let mut send_task = tokio::spawn(async move {
110110
while let Ok(msg) = rx.recv().await {
111111
// In any websocket error, break loop.
112-
if sender.send(Message::Text(msg)).await.is_err() {
112+
if sender.send(Message::Text(msg.into())).await.is_err() {
113113
break;
114114
}
115115
}

examples/testing-websockets/src/main.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ async fn integration_testable_handle_socket(mut socket: WebSocket) {
4848
while let Some(Ok(msg)) = socket.recv().await {
4949
if let Message::Text(msg) = msg {
5050
if socket
51-
.send(Message::Text(format!("You said: {msg}")))
51+
.send(Message::Text(format!("You said: {msg}").into()))
5252
.await
5353
.is_err()
5454
{
@@ -79,7 +79,7 @@ where
7979
while let Some(Ok(msg)) = read.next().await {
8080
if let Message::Text(msg) = msg {
8181
if write
82-
.send(Message::Text(format!("You said: {msg}")))
82+
.send(Message::Text(format!("You said: {msg}").into()))
8383
.await
8484
.is_err()
8585
{
@@ -137,7 +137,7 @@ mod tests {
137137
tokio::spawn(unit_testable_handle_socket(socket_write, socket_read));
138138

139139
test_tx
140-
.send(Ok(Message::Text("foo".to_owned())))
140+
.send(Ok(Message::Text("foo".into())))
141141
.await
142142
.unwrap();
143143

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

149-
assert_eq!(msg, "You said: foo");
149+
assert_eq!(msg.as_str(), "You said: foo");
150150
}
151151
}

examples/websockets-http2/src/main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ async fn ws_handler(
7575
res = ws.recv() => {
7676
match res {
7777
Some(Ok(ws::Message::Text(s))) => {
78-
let _ = sender.send(s);
78+
let _ = sender.send(s.to_string());
7979
}
8080
Some(Ok(_)) => {}
8181
Some(Err(e)) => tracing::debug!("client disconnected abruptly: {e}"),
@@ -85,7 +85,7 @@ async fn ws_handler(
8585
// Tokio guarantees that `broadcast::Receiver::recv` is cancel-safe.
8686
res = receiver.recv() => {
8787
match res {
88-
Ok(msg) => if let Err(e) = ws.send(ws::Message::Text(msg)).await {
88+
Ok(msg) => if let Err(e) = ws.send(ws::Message::Text(msg.into())).await {
8989
tracing::debug!("client disconnected abruptly: {e}");
9090
}
9191
Err(_) => continue,

examples/websockets/src/main.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ async fn ws_handler(
101101
/// Actual websocket statemachine (one will be spawned per connection)
102102
async fn handle_socket(mut socket: WebSocket, who: SocketAddr) {
103103
// send a ping (unsupported by some browsers) just to kick things off and get a response
104-
if socket.send(Message::Ping(vec![1, 2, 3])).await.is_ok() {
104+
if socket.send(Message::Ping(vec![1, 2, 3].into())).await.is_ok() {
105105
println!("Pinged {who}...");
106106
} else {
107107
println!("Could not send ping {who}!");
@@ -131,7 +131,7 @@ async fn handle_socket(mut socket: WebSocket, who: SocketAddr) {
131131
// connecting to server and receiving their greetings.
132132
for i in 1..5 {
133133
if socket
134-
.send(Message::Text(format!("Hi {i} times!")))
134+
.send(Message::Text(format!("Hi {i} times!").into()))
135135
.await
136136
.is_err()
137137
{
@@ -151,7 +151,7 @@ async fn handle_socket(mut socket: WebSocket, who: SocketAddr) {
151151
for i in 0..n_msg {
152152
// In case of any websocket error, we exit.
153153
if sender
154-
.send(Message::Text(format!("Server message {i} ...")))
154+
.send(Message::Text(format!("Server message {i} ...").into()))
155155
.await
156156
.is_err()
157157
{

0 commit comments

Comments
 (0)